mardi 14 août 2018

ReactJs set indeterminate state of custom bootstrap checkbox

I've made this checkbox which should be a "Three-State-Checkbox" it's using the indeterminate state not only as "visual-value" but also as a "real"-value. It work's fine if I'm only using the standard checkbox but if I use the bootstrap custom checkbox it doesn't work anymore because the ReactDOM.findDOMNode(this).indeterminate can't access the checkbox. So ReactDOM.findDOMNode(this).indeterminate = true; doesn't set indeterminate to true.

This is my component:

import React from "react";
import ReactDOM from 'react-dom';
import PropTypes from "prop-types";
import FormsStatic from "../FormsStatic";

class ThreeStateCheckbox extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value: this.props.value || "0",
            checked: false
        }
    }
    componentDidMount() {
        if (this.state.value != "0") {
            this.state.value == "1" ? this.setState({ checked: true }) : ReactDOM.findDOMNode(this).indeterminate = true;
        }
    }

    changeCbState() {
        if (this.state.value == "0") {
            this.state.value = "1";
            this.setState({ checked: true })
            ReactDOM.findDOMNode(this).indeterminate = false;
        }
        else if (this.state.value == "1") {
            this.state.value = "2";
            this.setState({ checked: false })
            ReactDOM.findDOMNode(this).indeterminate = true;
        }
        else {
            this.state.value = "0";
            this.setState({ checked: false })
            ReactDOM.findDOMNode(this).indeterminate = false;
        }
        this.props.onChange(this.state.value);
    }
    render() {
        const uniqueId = FormsStatic.guid();
        return (
            <div className="custom-control custom-checkbox">
                <input
                    type="checkbox"
                    className="custom-control-input"
                    id={"others-" + uniqueId}
                    checked={this.state.checked}
                    onChange={() => {
                        this.changeCbState();
                    }}
                />
                <label className="custom-control-label" htmlFor={"others-" + uniqueId}>
                </label>
            </div>
        );
    }
}

ThreeStateCheckbox.propTypes = {
    className: PropTypes.string,
    value: PropTypes.string,
    onChange: PropTypes.func
}

export default ThreeStateCheckbox;

What is the way to set the indeterminate of the checkbox?




Aucun commentaire:

Enregistrer un commentaire