Want to change checkbox in react correctly? The first option will be better if you have a lot of form and components. You can handle all with one handler.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function SomeForm() { const [formData, setFormData] = useState({ name: "", accept: false }); const onFieldChange = ({ target: { name, value, checked } }) => { if (typeof checked !== 'undefined') { // checking if we have a "checked" field inside target setFormData({ [name]: checked }); } setFormData({ [name]: value }); } return ( <form> <input type="text" name="name" value={formData.name} onChange={onFieldChange} /> <input type="checkbox" name="accept" checked={formData.accept} onChange={onFieldChange} /> </form> ) } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.