Handling Multiple Checkboxes in React with useState
Learn how to implement and manage multiple checkboxes in React applications using the `useState` hook. This tutorial provides a practical example demonstrating how to dynamically render checkboxes, track selections, and retrieve selected values, enhancing user interaction and data handling.
Handling Multiple Checkboxes in React
Introduction to Multiple Checkboxes
Multiple checkboxes allow users to select one or more options from a list. This tutorial shows how to implement multiple checkboxes in React and retrieve the selected values using the `useState` hook.
Implementing Multiple Checkboxes in React
This example dynamically renders checkboxes based on an array of categories. It uses a `Map` to store which checkboxes are selected and provides a submit button to display the selected items.
Multiple Checkboxes Example
import React, { useState } from 'react';
const App = () => {
const [categories, setCategories] = useState([
{ id: 1, value: "Angular" },
{ id: 2, value: "React" },
{ id: 3, value: "PHP" },
{ id: 4, value: "Laravel" },
]);
const [checkedItems, setCheckedItems] = useState(new Map());
const handleChange = (event) => {
const isChecked = event.target.checked;
const item = event.target.value;
setCheckedItems(prev => new Map(prev).set(item, isChecked));
};
const handleSubmit = (event) => {
console.log(checkedItems);
event.preventDefault();
};
return (
<form onSubmit={handleSubmit}>
<h2>Examples of Multiple Checkbox in React</h2>
{categories.map((item) => (
<div key={item.id}>
<input
type="checkbox"
id={item.value}
value={item.value}
checked={checkedItems.get(item.value) || false}
onChange={handleChange}
/>
<label htmlFor={item.value}>{item.value}</label>
</div>
))}
<button type="submit">Submit</button>
</form>
);
};
export default App;
The `handleChange` function updates the `checkedItems` state whenever a checkbox's checked status changes. The `handleSubmit` function logs the selected items to the console.