About
This page shows you how you can create a checkbox in React.
This example is written in JSX and shows you a controlled component.
The react forms components input accept a value attribute that is used to implement a controlled component.
Example
- The component
function Checkbox() {
const [checked, setChecked] = React.useState(false);
console.log('The checkbox is '+( !checked ? 'not' : '')+' checked');
return (
<div className="form-check form-switch m-3">
<input onChange={(e) => setChecked(e.target.checked)}
className="form-check-input" type="checkbox"
role="switch" id="previewSwitch" checked={checked}/>
<label className="form-check-label" htmlFor="previewSwitch">Toggle checkbox</label>
</div>
);
}
- Result: