Complete the code to create a checkbox input that updates state when clicked.
const [checked, setChecked] = useState(false); return ( <input type="checkbox" checked={checked} onChange=[1] /> );
The onChange handler toggles the checked state by setting it to the opposite of its current value.
Complete the code to handle a radio button group that updates the selected option in state.
const [selected, setSelected] = useState('option1'); return ( <input type="radio" value="option1" checked={selected === 'option1'} onChange=[1] /> );
The onChange handler updates the selected state to the value of the clicked radio button.
Fix the error in the checkbox handler to correctly update state based on the checkbox's checked property.
const [checked, setChecked] = useState(false);
function handleChange(e) {
setChecked([1]);
}
return <input type="checkbox" checked={checked} onChange={handleChange} />;The checkbox's checked state is found in e.target.checked, not e.target.value or other properties.
Fill both blanks to create a controlled radio button group that updates state on change.
const [choice, setChoice] = useState('A'); return ( <input type="radio" value="A" checked={choice [1] 'A'} onChange=[2] /> );
The checked attribute compares choice with 'A' using strict equality. The onChange updates choice to the clicked value.
Fill the two blanks to create a checkbox group that updates an array of selected options in state.
const [selected, setSelected] = useState([]);
function handleCheckboxChange(e) {
const value = e.target.value;
if (selected.includes(value)) {
setSelected(selected.filter(item => item [1] value));
} else {
setSelected([...selected, [2]]);
}
}
return (
<input type="checkbox" value="opt1" checked={selected.includes('opt1')} onChange={handleCheckboxChange} />
);To remove an item, filter with (item => item !== value), keeping items !== value (removes matching). To add, spread selected and add value.