A short React tutorial by example for beginners on how to create an indeterminate React Checkbox which uses an indeterminate state (also called tri state ).
Letâs start with a checkbox example from our previous tutorial:
Now we want to extend the functionality of this checkbox for handling a tri state instead of a bi state. First, we need to transform our state from a boolean to an enum, because only this way we can create a tri state:
We have the same behavior as before, but enabled us to have more than two states for our checkbox.
Next comes the indeterminate state of a checkbox. Unfortunately it cannot be assigned via HTML and we need to use an imperative DOM manipulation here. Fortunately React has the concept of refs which gives React developers access to DOM elements:
By having access to the checkbox element, we can set and unset the checked state imperatively instead of using the HTML in a declarative way:
Reactâs useEffect Hook executes its passed side-effect function every time a variable in the dependency array (here: value ) changes. Then in the side-effect function we evaluate the value: if it is checked, we set the checkboxâs internal HTML state programmatically to checked; and vice versa for the unchecked state.
Finally, we can assign the indeterminate state this way too:
And donât forget to assign the proper value on state change in the first place:
Thatâs it. We transformed our React checkbox component from a bi state to a tri state by introducing the indeterminate state. I hope this tutorial is useful to you if you happen to need a checkbox with three states.