Mark As Completed Discussion

Form Handling in React

Working with forms and handling form input is a common task in web development, and React provides convenient ways to handle this.

In React, you can create a form component that maintains its own state separate from the global state. This makes it easier to manage form inputs and perform form validation.

Here's an example of a simple form component in React:

JAVASCRIPT
1function MyForm() {
2  const [name, setName] = React.useState('');
3  const [email, setEmail] = React.useState('');
4
5  const handleSubmit = () => {
6    // Handle form submission logic
7  };
8
9  return (
10    <form onSubmit={handleSubmit}>
11      <label>
12        Name:
13        <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
14      </label>
15      <label>
16        Email:
17        <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
18      </label>
19      <button type="submit">Submit</button>
20    </form>
21  );
22}
23
24ReactDOM.render(<MyForm />, document.getElementById('root'));

In this example, we define a form component MyForm that uses the useState hook to manage the state of the form inputs (name and email).

The handleSubmit function is called when the form is submitted. You can implement the logic to handle form submission in this function.

The form component renders an HTML form element with two input fields (name and email) and a submit button. The value and onChange attributes are used to bind the input fields to the state variables.

Try running the code snippet above and see how the form behaves. You can enter values in the input fields and click the submit button to see the form submission logic in action.

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