Checkbox list example in React
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
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
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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 className="app"> <h4>Checkbox list in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4> <div className='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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | 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 className="app"> <h4>Checkbox list in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4> <div className='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..!! đŸ™‚