Creating a Basic Form
To create a basic form in React, we can use the form
element along with different form input components like input
, textarea
, and select
. These form input components can be controlled by state using React's useState
hook.
Let's start by creating a simple form with input fields for name and email:
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 import the necessary dependencies including React and the
useState
hook. - We define a functional component
BasicForm
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 submission behavior and displays an alert with the values ofname
andemail
. - 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 BasicForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
alert(`Name: ${name}, Email: ${email}`);
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor='name'>Name:</label>
<input type='text' id='name' value={name} onChange={(e) => setName(e.target.value)} />
<label htmlFor='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