Forms are an essential part of any web application. In React, handling user inputs involves creating forms with controlled components, which means that the form data is managed by the state of the React component. React provides a straightforward way to handle forms by using controlled components, where form elements like <input>
, <textarea>
, and <select>
are bound to the component’s state.
1. Controlled Components
A controlled component is an input element whose value is controlled by React state. Instead of the DOM managing the form data, React manages it through state. This means the value of the input is determined by the state variable and any changes to the input will update the state.
Example of a Controlled Input:
import React, { useState } from 'react';
function ControlledForm() {
const [name, setName] = useState('');
const handleChange = (event) => {
setName(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
alert(`Form submitted with name: ${name}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
export default ControlledForm;
In this example:
- The
<input>
field’s value is tied to the state variablename
. - The
handleChange
function updates the state whenever the user types into the input field. - The
handleSubmit
function handles the form submission, preventing the default form submission behavior and displaying an alert with the submitted name.
2. Multiple Inputs in a Form
When you have multiple input fields in a form, each input can be controlled by its own state or a single state object. Here’s an example where multiple inputs are controlled using a single state object.
Example of Multiple Controlled Inputs:
import React, { useState } from 'react';
function MultiInputForm() {
const [formData, setFormData] = useState({ name: '', email: '' });
const handleChange = (event) => {
const { name, value } = event.target;
setFormData({
...formData,
[name]: value,
});
};
const handleSubmit = (event) => {
event.preventDefault();
alert(`Form submitted with Name: ${formData.name}, Email: ${formData.email}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
/>
</label>
<label>
Email:
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
</label>
<button type="submit">Submit</button>
</form>
);
}
export default MultiInputForm;
In this example:
- The form data is stored in a single state object (
formData
). - Each input field (
name
andemail
) is given aname
attribute, which corresponds to the keys in theformData
object. - The
handleChange
function updates the correct key in the state object based on thename
of the input field.
3. Handling Textarea Inputs
You can use the same approach to handle textarea
inputs in React. The value
of a textarea
can be controlled by the component’s state.
Example with textarea
:
import React, { useState } from 'react';
function TextareaForm() {
const [message, setMessage] = useState('');
const handleChange = (event) => {
setMessage(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
alert(`Form submitted with message: ${message}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Message:
<textarea value={message} onChange={handleChange}></textarea>
</label>
<button type="submit">Submit</button>
</form>
);
}
export default TextareaForm;
4. Handling Select Inputs
For select
inputs, you also bind the value
to the component’s state and update it based on user selection.
Example with select
:
import React, { useState } from 'react';
function SelectForm() {
const [selectedOption, setSelectedOption] = useState('');
const handleChange = (event) => {
setSelectedOption(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
alert(`Form submitted with selected option: ${selectedOption}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Choose an option:
<select value={selectedOption} onChange={handleChange}>
<option value="">Select...</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
</label>
<button type="submit">Submit</button>
</form>
);
}
export default SelectForm;
5. Handling Form Submission
When handling form submissions, React allows you to manage the form data directly using the state. By calling event.preventDefault()
, you prevent the default form submission behavior, which would typically cause a page reload.
In most forms, you will handle the submission either by updating the state or sending the data to an API or server.
Example with Form Submission:
import React, { useState } from 'react';
function SubmitForm() {
const [email, setEmail] = useState('');
const handleChange = (event) => {
setEmail(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
console.log(`Form submitted with email: ${email}`);
// You can also send data to an API or perform other actions here.
};
return (
<form onSubmit={handleSubmit}>
<label>
Email:
<input type="email" value={email} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
export default SubmitForm;
6. Handling Checkboxes and Radio Buttons
Checkboxes and radio buttons also require special handling since their values are either true/false (checkboxes) or selected/unselected (radio buttons).
Example with Checkbox:
import React, { useState } from 'react';
function CheckboxForm() {
const [isChecked, setIsChecked] = useState(false);
const handleChange = (event) => {
setIsChecked(event.target.checked);
};
const handleSubmit = (event) => {
event.preventDefault();
alert(`Checkbox is ${isChecked ? 'checked' : 'unchecked'}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Agree to Terms:
<input type="checkbox" checked={isChecked} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
}
export default CheckboxForm;
7. Summary
Element | State Handling | Example |
---|---|---|
Text Inputs | Use controlled components by binding the value to state. | <input type="text" value={state} onChange={handleChange} /> |
Textareas | Use controlled components for multi-line input. | <textarea value={state} onChange={handleChange}></textarea> |
Select Inputs | Bind the selected value to state. | <select value={state} onChange={handleChange}><option>...</option></select> |
Checkboxes | Bind the checked state to state using checked . | <input type="checkbox" checked={state} onChange={handleChange} /> |
Radio Buttons | Bind the selected radio option to state. | <input type="radio" checked={state} onChange={handleChange} /> |
Form Submission | Prevent default form behavior and handle submission via state. | event.preventDefault() and alert(formData) |