In this blog post, we will discuss how to add a checkbox in a React component that is checked by default but editable by the user.
Initially, I had a simple checkbox in my React component:
<input name="enable" type="checkbox" />
However, setting a checked
attribute with the value of "checked"
didn’t work as expected. The checkbox state remained unchangeable.
To resolve this issue, I discovered that the defaultChecked
attribute should be used instead:
<input name="enable" type="checkbox" defaultChecked={true} />
By setting defaultChecked
to true
, the checkbox will be checked by default when the component is rendered.
Furthermore, if you need the checkbox to be checked based on a variable value (such as retrieving the value from a database in an editing form), you can do the following:
<input name="enable" type="checkbox" defaultChecked={existing_enable_value} />
In the above example, existing_enable_value
represents the value that determines whether the checkbox should be checked.
By following these techniques, you can add an editable checkbox that is checked by default in your React components.
Tags: React, checkbox, defaultChecked, variable, database