React, how to make a checked checkbox editable
How to add a checkbox that defaults to checked but it's editable in React
I had a checkbox in a React component:
<input name="enable" type="checkbox" />
and I wanted it to be checked by default, yet the user could change its value.
Using
<input name="enable" type="checkbox" checked="checked" />
didn’t work. The checkbox state could not be changed.
The solution was to use the defaultChecked
attribute:
<input name="enable" type="checkbox" defaultChecked={true} />
If the checkbox needs to be checked depending if the value was checked in a variable (for example in an editing form when you are getting the actual value from the database) you can use
<input name="enable" type="checkbox" defaultChecked={existing_enable_value} />
→ Get my React Beginner's Handbook
I wrote 21 books to help you become a better developer:
- HTML Handbook
- Next.js Pages Router Handbook
- Alpine.js Handbook
- HTMX Handbook
- TypeScript Handbook
- React Handbook
- SQL Handbook
- Git Cheat Sheet
- Laravel Handbook
- Express Handbook
- Swift Handbook
- Go Handbook
- PHP Handbook
- Python Handbook
- Linux Commands Handbook
- C Handbook
- JavaScript Handbook
- Svelte Handbook
- CSS Handbook
- Node.js Handbook
- Vue Handbook