D
D
Dmitry Markov2020-04-27 23:21:49
React
Dmitry Markov, 2020-04-27 23:21:49

How to make initial state of checkbox?

this.props.checked stores the initial state of the checkbox. But at the time of rendering, it is still empty, in render ( ) you cannot write state, Tell me what the thread is. Code below

export default class Checkbox extends Component {
    constructor(props) {
        super(props);

        this.state = {
            checked: this.props.checked
        }

        this.onChange = this.onChange.bind(this);
    }
    onChange(event) {
        let checked = event.target.checked;
        if( this.props.func )
            this.props.func(checked);


        this.setState({checked});
    }
    render() {
        const { name, children } = this.props;

        return(
            <label className="checkbox">
                <input name={name} type="checkbox" className="checkbox__input" onChange={this.onChange} checked={this.state.checked} />
                <span className="checkbox__text">{children}</span>
            </label>
        )
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Gamega, 2020-04-28
@En-Tilza

<input type="checkbox" defaultChecked={checked} />

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question