How to create multiple checkbox with react and FormData
Posted 4 years ago by Ryan Dhungel
Category: Web Development React
Viewed 14711 times
Estimated read time: 2 minutes
- Ever wanted to create a multiple checkbox with react. If you do then you will find this article very helpful.
- In the code below you can see how I have created a form with multiple checkbox where users can check/uncheck to select/deselect categories.
- I have pushed category id's in the state for my use case. Depending on your use case you can push category id, name or slug.
- I have also used formData because I was not posting JSON data to my API
- Instead I was sending FormData because I had to post image files too.
- Either way you should have no problems to acheive what you are trying to acheive.
- You can simply copy paste the entire code block below to give it a try!
Example react app with multiple checkbox
import { useState, useEffect } from "react";
const App = () => {
const [formData, setFormData] = useState("");
const [checked, setChecked] = useState([]); // categories
const [categories, setCategories] = useState([
{ _id: "5d7c7653427efd4400201e0e", name: "JavaScript", slug: "javascript" },
{ _id: "5d7c7662427efd4400201e11", name: "VueJs", slug: "vuejs" },
{ _id: "5d7c79df427efd4400201e1e", name: "Firebase", slug: "firebase" }
]);
useEffect(() => {
setFormData(new FormData());
}, []);
const handleToggle = c => () => {
// return the first index or -1
const clickedCategory = checked.indexOf(c);
const all = [...checked];
if (clickedCategory === -1) {
all.push(c);
} else {
all.splice(clickedCategory, 1);
}
console.log(all);
setChecked(all);
formData.set("categories", all);
};
const showCategories = () => {
return categories.map((c, i) => (
<li key={i} className="list-unstyled">
<input
onChange={handleToggle(c._id)}
type="checkbox"
className="mr-2"
/>
<label className="form-check-label">{c.name}</label>
</li>
));
};
return (
<div>
<h2>Categories</h2>
{showCategories()}
<h2>Form Data</h2>
{JSON.stringify(...formData)}
</div>
);
};
export default App;