I have 2 checkboxes A and B. I want to check whether checkbox B is checked or not on change of checkbox A and vice versa. Also I want to change checkbox B on change of checkbox A. How can we achieve that in react.js.
>Solution :
You can to create a state for both of them.
This way you’ll have access to it whenever needed.
Example:
function App() {
const [state, setState] = useState({
firstCheckbox: false,
secondCheckbox: false
})
const handleChange = (e) => {
setState(prev => ({
...prev,
[e.target.name]: e.target.value
}))
}
return (
<>
<input
name='firstCheckbox'
type='checkbox'
checked={state.firstCheckbox}
onChange={handleChange}
/>
<input
name='secondCheckbox'
type='checkbox'
checked={state.secondCheckbox}
onChange={handleChange}
/>
</>
)
}
Currently in this example, each checkbox relates to it’s own state.
However, you can easily adjust the handleChange function based on your needs.