EN
React - three-state checkbox with Material-UI (with indeterminate property)
10 points
In this short article we would like to show how to create three-state checkbox in React with Material-UI Checkbox
component. Three-state checkbox we understand as checkbox that is able to use three states: true
, false
and null
as unset value.
Note: check this article to see online runnable example how to get same effect with HTML
input
element.
Practical example:
xxxxxxxxxx
1
import MaterialCheckbox from '@material-ui/core/Checkbox';
2
import React, { forwardRef, Ref, useEffect, useState } from 'react';
3
4
const Checkbox = ({ name, checked, onFocus, onChange, onBlur }, ref) => {
5
const [localChecked, setLocalChecked] = useState(checked ?? null);
6
useEffect(() => setLocalChecked(checked ?? null), [checked]);
7
const handleChange = () => {
8
switch (localChecked) {
9
case true:
10
setLocalChecked(false);
11
break;
12
case false:
13
setLocalChecked(null);
14
break;
15
default:
16
setLocalChecked(true);
17
break;
18
}
19
if (onChange) {
20
onChange(localChecked);
21
}
22
};
23
const handleBlur = () => {
24
if (onBlur) {
25
onBlur(localChecked);
26
}
27
};
28
return (
29
<MaterialCheckbox
30
inputRef={ref}
31
name={name}
32
checked={!!localChecked}
33
indeterminate={localChecked === null}
34
onFocus={onFocus}
35
onChange={handleChange}
36
onBlur={handleBlur}
37
/>
38
);
39
};
40
41
export default forwardRef(Checkbox);