Introduction to React Forms
In React, forms are an essential part of building interactive user interfaces. Whether you want to capture user input, collect data, or handle user actions, forms play a crucial role in facilitating these interactions.
React forms can be created using the form
HTML element along with various form input elements like input
, textarea
, select
, etc. These form input elements can be controlled components, meaning their values are controlled by the state of a React component.
Here's an example of a basic form in React:
JAVASCRIPT
1import React, { useState } from 'react';
2
3export default function FormExample() {
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 for='name'>Name:</label>
15 <input type='text' id='name' value={name} onChange={(e) => setName(e.target.value)} />
16
17 <label for='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 above example,
- We start by importing the necessary dependencies including React and the
useState
hook for managing the form state. - We define a functional component
FormExample
that renders the form. - We declare two state variables
name
andemail
using theuseState
hook to store the values of the input fields. - We implement a
handleSubmit
function that will be called when the form is submitted. It prevents the default form submit behavior, and displays an alert with the values ofname
andemail
fields. - We use the
value
prop to bind the value of each input field to its respective state variable. And theonChange
prop to update the state when the user types in the input fields. - Finally, we render the form with the input fields for
name
andemail
, and a submit button.
Feel free to modify the code and test it out in your local development environment. Try adding additional form input elements and handle their values in the state. Happy coding!
xxxxxxxxxx
23
import React, { useState } from 'react';
export default function FormExample() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
alert(`Name: ${name}, Email: ${email}`);
};
return (
<form onSubmit={handleSubmit}>
<label for='name'>Name:</label>
<input type='text' id='name' value={name} onChange={(e) => setName(e.target.value)} />
<label for='email'>Email:</label>
<input type='email' id='email' value={email} onChange={(e) => setEmail(e.target.value)} />
<button type='submit'>Submit</button>
</form>
);
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment