Checkbox list example in React
📅January 29, 2022
In this article, you will learn how to create a checkbox list in React. Here we will simply create a list of items with input checkboxes and handle the selection using React Hooks.
Checkout more articles on ReactJS
- Password and Confirm Password validation in React
- Create a toggle switch in React
- MultiSelect dropdown in React
- Handle drag over and out in React
- Barcode scanner in React
Let’s create an example where we will render the list of languages and based on selection we will show you the selected languages.
Demo Application
Output - Checkbox list example in React - Clue Mediator
Steps to create a checkbox list in React
1. Render a list of items using the checkbox
Let’s consider the following languages and render it as a checkbox list.
import React from 'react';
const languageList = [
{ value: "english", label: "English" },
{ value: "hindi", label: "Hindi" },
{ value: "spanish", label: "Spanish" },
{ value: "arabic", label: "Arabic" }
];
function App() {
return (
<div class="app">
<h4>Checkbox list in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4>
<div class="title">Select languages from the list</div>
{languageList.map((x, i) => <label key={i}>
<input type="checkbox" name="lang" value={x.value}> {x.label}
</label>)}
</div>
);
}
export default App;
2. Handle a checkbox selection
Capture the `onChange` event to handle the checkbox selection and store the selected values in the state variable.
import React, { useState } from 'react';
const languageList = [
{ value: "english", label: "English" },
{ value: "hindi", label: "Hindi" },
{ value: "spanish", label: "Spanish" },
{ value: "arabic", label: "Arabic" }
];
function App() {
const [lang, setLang] = useState([]);
const handleChange = e => {
const { value, checked } = e.target;
if (checked) {
// push selected value in list
setLang(prev => [...prev, value]);
} else {
// remove unchecked value from the list
setLang(prev => prev.filter(x => x !== value));
}
}
return (
<div class="app">
<h4>Checkbox list in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4>
<div class="title">Select languages from the list</div>
{languageList.map((x, i) => <label key={i}>
<input type="checkbox" name="lang" value={x.value} onchange={handleChange}> {x.label}
</label>)}
<div>Selected languages: {lang.length ? lang.join(', ') : null}</div>
</div>
);
}
export default App;
3. Output
Run the application and check the output in the browser.
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂