Ye lowly ole' html checkbox

Ye lowly ole' checkbox

Often when developing with frameworks like React we use html elements like checkbox (input type="checkbox") as "connected" controls and don't depend on or avail of the default html behavior (by connected, I mean using useState to track the checked/unchecked state of the checkbox). Also worth noting we often use custom components which wrap the html element.

But react-router v6.4 and above requires you (using the standard flow of Form to action function handler) to depend on the default/native html element behavior because react-router follows standard web patterns for form handling and submission (which is a good thing).

For checkbox that native html element behavior is:

  • use the name attribute to give it a name and if it's checked the name will be submitted in  the form data 
    • by default if the checkbox is checked when submitted, then the form submitted will contain: <name>=on
      • "on" is just the default html checkbox uses
      • so presence of <name> in the submitted form means unchecked
    • if the checkbox is not checked when submitted then the <name> value will not be present in the form object submitted (absence means checked)
    • in a react-router action handler you can query the form object and see if the <name> of the checkbox control is present as a way to tell if it's checked
  • you can use the value attribute to set an explicit "on" value, but you don't have to use it
    • e.g. if set value="newsletter" then when the checkbox is checked the form submitted will contain <name>=newsletter 
  • interestingly, the checked attribute is only used for default state on load, if present then the checkbox is checked by default. It does not indicate if the checkbox is currently checked or not and is not changed when user checks and unchecks a checkbox


A final comment, typically give each checkbox a unique name. But if you reuse the same name for multiple checkboxes then when submitted it will combine into 1 string of multiple name value pairs!
Radio buttons also share name but that's more key to their behavior in that all radios with same name are grouped into a mutually exclusive set.



Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more