React, how to make a checked checkbox editable
New Course Coming Soon:
Get Really Good at Git
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} />
Are you intimidated by Git? Can’t figure out merge vs
rebase? Are you afraid of screwing up something any time
you have to do something in Git? Do you rely on ChatGPT
or random people’s answer on StackOverflow to fix your
problems? Your coworkers are tired of explaining Git to
you all the time? Git is something we all need to use,
but few of us really master it. I created this course to
improve your Git (and GitHub) knowledge at a radical
level. A course that helps you feel less frustrated with
Git. Launching Summer 2024. Join the waiting list!
→ Get my
React Beginner's Handbook
→ Read my full
React Tutorial
on The Valley of Code
Here is how can I help you:
- COURSES where I teach everything I know
- THE VALLEY OF CODE your web development manual
- BOOTCAMP 2024 cohort in progress, next edition in 2025
- BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
- SOLO LAB everything I know about running a lifestyle business as a solopreneur
- Interesting links collection
- Follow me on X