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:
import MaterialCheckbox from '@material-ui/core/Checkbox';
import React, { forwardRef, Ref, useEffect, useState } from 'react';
const Checkbox = ({ name, checked, onFocus, onChange, onBlur }, ref) => {
const [localChecked, setLocalChecked] = useState(checked ?? null);
useEffect(() => setLocalChecked(checked ?? null), [checked]);
const handleChange = () => {
switch (localChecked) {
case true:
setLocalChecked(false);
break;
case false:
setLocalChecked(null);
break;
default:
setLocalChecked(true);
break;
}
if (onChange) {
onChange(localChecked);
}
};
const handleBlur = () => {
if (onBlur) {
onBlur(localChecked);
}
};
return (
<MaterialCheckbox
inputRef={ref}
name={name}
checked={!!localChecked}
indeterminate={localChecked === null}
onFocus={onFocus}
onChange={handleChange}
onBlur={handleBlur}
/>
);
};
export default forwardRef(Checkbox);