Languages
[Edit]
EN

React - three-state checkbox with Material-UI (with indeterminate property)

10 points
Created by:
Welsh
902

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);
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - three-state checkbox (with Material-UI)
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join