EN
React - three-state checkbox (with indeterminate property)
12 points
In this short article, we would like to show you how to create three-state checkbox in React with input
checkbox
element that uses built-in indeterminate
property. Three-state checkbox we understand as checkbox that is able to get three states: true
, false
and null
as unset value.
Practical example:
xxxxxxxxxx
1
// import React from 'react';
2
// import ReactDOM from 'react-dom';
3
4
const updateInput = (ref, checked) => {
5
const input = ref.current;
6
if (input) {
7
input.checked = checked;
8
input.indeterminate = checked == null;
9
}
10
};
11
12
const ThreeStateCheckbox = ({name, checked, onChange}) => {
13
const inputRef = React.useRef(null);
14
const checkedRef = React.useRef(checked);
15
React.useEffect(() => {
16
checkedRef.current = checked;
17
updateInput(inputRef, checked);
18
}, [checked]);
19
const handleClick = () => {
20
switch (checkedRef.current) {
21
case true:
22
checkedRef.current = false;
23
break;
24
case false:
25
checkedRef.current = null;
26
break;
27
default: // null
28
checkedRef.current = true;
29
break;
30
}
31
updateInput(inputRef, checkedRef.current);
32
if (onChange) {
33
onChange(checkedRef.current);
34
}
35
};
36
return (
37
<input ref={inputRef} type="checkbox" name={name} onClick={handleClick} />
38
);
39
};
40
41
const App = () => {
42
const [checked, setChecked] = React.useState(null);
43
const handleChange = (checked) => {
44
console.log(`checked: ${checked}`);
45
};
46
return (
47
<ThreeStateCheckbox checked={checked} onChange={handleChange} />
48
);
49
};
50
51
const root = document.querySelector('#root');
52
ReactDOM.render(<App />, root );