Mark As Completed Discussion

Handling Form Submission

Now that we have created a basic form with input fields, it's time to implement the logic to handle form submission and capture user input.

In our example, we have already defined the handleSubmit function that will be called when the form is submitted.

JAVASCRIPT
1import React, { useState } from 'react';
2
3export default function BasicForm() {
4  const [name, setName] = useState('');
5  const [email, setEmail] = useState('');
6
7  const handleSubmit = (e) => {
8    e.preventDefault();
9    alert(`Name: ${name}, Email: ${email}`);
10  };
11
12  return (
13    <form onSubmit={handleSubmit}>
14      <label htmlFor='name'>Name:</label>
15      <input type='text' id='name' value={name} onChange={(e) => setName(e.target.value)} />
16
17      <label htmlFor='email'>Email:</label>
18      <input type='email' id='email' value={email} onChange={(e) => setEmail(e.target.value)} />
19
20      <button type='submit'>Submit</button>
21    </form>
22  );
23}

In the code above, we have used the preventDefault() method to prevent the default form submission behavior. Instead, we display an alert with the values entered by the user.

You can test the form by entering values in the input fields and clicking the submit button. When the form is submitted, you should see an alert with the name and email values.

Feel free to modify the code and add additional form input elements or customize the submit logic to meet your requirements. Happy coding!

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment