Renders a checkbox list that uses a callback function to pass its selected value/values to the parent component.
- Use the
useState()
hook to create thedata
state variable and use theoptions
prop to initialize its value. - Create a
toggle
function that uses the spread operator (...
) andArray.prototype.splice()
to update thedata
state variable and call theonChange
callback with anychecked
options. - Use
Array.prototype.map()
to map thedata
state variable to individual<input type="checkbox">
elements, each one wrapped in a<label>
, binding theonClick
handler to thetoggle
function.
const MultiselectCheckbox = ({ options, onChange }) => { const [data, setData] = React.useState(options); const toggle = index => { const newData = [...data]; newData.splice(index, 1, { label: data[index].label, checked: !data[index].checked }); setData(newData); onChange(newData.filter(x => x.checked)); }; return ( <> {data.map((item, index) => ( <label key={item.label}> <input readOnly type="checkbox" checked={item.checked || false} onClick={() => toggle(index)} /> {item.label} </label> ))} </> ); };
Examples
const options = [{ label: 'Item One' }, { label: 'Item Two' }]; ReactDOM.render( <MultiselectCheckbox options={options} onChange={data => { console.log(data); }} />, document.getElementById('root') );
Recommended snippets
Renders an uncontrolled
<select>
element that uses a callback function to pass its value to the parent component.Renders an uncontrolled range input element that uses a callback function to pass its value to the parent component.
Renders an uncontrolled
<textarea>
element that uses a callback function to pass its value to the parent component.