Mark As Completed Discussion

React Forms

In React, forms are an essential part of building interactive user interfaces. They allow users to input data and submit it to the server for processing.

To create a form in React, you can use the <form> element and various input elements such as <input>, <textarea>, and <select>. These elements have an onChange event that fires whenever their value changes, allowing you to capture user input.

Here's an example of a basic React form:

SNIPPET
1// Example of a basic React form
2
3import React, { useState } from 'react';
4
5function MyForm() {
6  const [name, setName] = useState('');
7  const [email, setEmail] = useState('');
8
9  const handleSubmit = (e) => {
10    e.preventDefault();
11    console.log('Form submitted!');
12    console.log('Name:', name);
13    console.log('Email:', email);
14  }
15
16  return (
17    <form onSubmit={handleSubmit}>
18      <label>
19        Name:
20        <input type='text' value={name} onChange={(e) => setName(e.target.value)} />
21      </label>
22      <br />
23      <label>
24        Email:
25        <input type='email' value={email} onChange={(e) => setEmail(e.target.value)} />
26      </label>
27      <br />
28      <button type='submit'>Submit</button>
29    </form>
30  );
31}
32
33export default MyForm;

In the example above, we create a component MyForm that renders a form with two input fields for name and email. We use the useState hook to manage the form state.

The onChange event is used to update the state when the input values change. The handleSubmit function is called when the form is submitted, preventing the default form submission behavior and logging the form data to the console.

By leveraging React's form handling capabilities, you can create powerful and interactive forms in your applications.

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