ReactJs Multiple Checkbox
Syntax
<input type="checkbox" value={value} onChange={handleChange} />
Example
import React, { useState } from "react";
const CheckboxExample = () => {
const [checkedItems, setCheckedItems] = useState({});
const handleChange = (event) => {
setCheckedItems({
...checkedItems,
[event.target.name]: event.target.checked,
});
};
return (
<div>
<h2>Choose as many options as you like:</h2>
<form>
<label>
Option 1:
<input
type="checkbox"
name="option 1"
checked={checkedItems["option 1"] || false}
onChange={handleChange}
/>
</label>
<label>
Option 2:
<input
type="checkbox"
name="option 2"
checked={checkedItems["option 2"] || false}
onChange={handleChange}
/>
</label>
<label>
Option 3:
<input
type="checkbox"
name="option 3"
checked={checkedItems["option 3"] || false}
onChange={handleChange}
/>
</label>
<label>
Option 4:
<input
type="checkbox"
name="option 4"
checked={checkedItems["option 4"] || false}
onChange={handleChange}
/>
</label>
</form>
</div>
);
};
export default CheckboxExample;
Output
The output will be a list of options that have been checked.
Explanation
Checkboxes are a form element that allow users to select multiple options from a list. In React, checkboxes are created using the input
element. When users interact with a checkbox, the onChange
event fires. This event can be used to update the state of the component to reflect which options have been checked.
Use
Multiple checkboxes are often used in forms where the user needs to select from a list of options. For example, a user might need to select which products they are interested in, or which colors they prefer.
Important Points
- Use the
checked
attribute to set the initial state of the checkboxes. - The
onChange
event should be used to update the state when the user interacts with a checkbox. - When updating the state, use the
name
attribute to identify which checkbox has been changed.
Summary
In this article, we learned how to create multiple checkboxes in React. We examined the syntax, provided an example, explained the output, and discussed the use cases, important points, and summary.