Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { Component } from 'react';
- import Checkbox from '@material-ui/core/Checkbox';
- /**
- * Tri-state wrapper for material-ui checkbox
- * @prop {boolean | null} checked - the state of the checkbox
- * true means checked
- * false means unchecked
- * null (or undefined) means indeterminate
- * @prop {(event, checked: boolean | null) => void} onChange
- * called whenever the state of the checkbox changes
- * note that `event.target.checked` cannot be relied on
- * as it can with Checkbox
- * This component also passes all other props to the underlying
- * Checkbox *except* for `indeterminate`
- */
- export default class TriStateCheckbox extends Component {
- static getDerivedStateFromProps ({ checked }) {
- return { checked };
- }
- constructor() {
- super();
- this.state = { checked: null };
- }
- onTouch = (e) => {
- let { checked } = this.state;
- // ... -> null -> false -> true -> ...
- if (checked === false) {
- checked = true;
- } else if (checked === true) {
- checked = null;
- } else {
- checked = false;
- }
- this.setState({ checked }, () => this.props.onChange(e, checked));
- }
- render() {
- // prevent some props from being passed
- let { checked: c, indeterminate: i, onChange: oc, ...rest } = this.props;
- let { checked } = this.state;
- let indeterminate = false;
- if (checked == null) { // deliberate ==, undefined or null is fine
- indeterminate = true; // shows - in box, overriding checked
- checked = false; // if indeterminate, F means gray, T means color
- }
- return <Checkbox
- checked={checked}
- indeterminate={indeterminate}
- onChange={this.onTouch}
- { ...rest }
- />
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement