jeudi 8 juin 2017

React.js - Value of checkbox not reflecting initial state

I'm rendering checkboxes with the following code:

return (
    <div className='day'>
        <label className='name'>
            {day.name}
            <input
                type='checkbox'
                checked={this.state.available}
                onChange={this.handleAvailableChange}
                />
        </label>
        {this.state.available}

        <label>
            <span className='day-select-label'>From</span>
            <Select
                name={day.name}
                placeholder="Start time"
                options={hours}
                value={this.state.startTime}
                onChange={this.handleStartTimeChange}
                disabled={!this.state.available}
                />
        </label>

        <label>
            <span className='day-select-label'>To</span>
            <Select
                name={day.name}
                placeholder="End time"
                options={hours}
                value={this.state.endTime}
                onChange={this.handleEndTimeChange}
                disabled={!this.state.available}
                />
        </label>
    </div>
);

And I'm setting my state in the constructor of my component with the following:

constructor(props){
    super(props)
    this.state = {
        startTime: this.props.startTime,
        endTime: this.props.endTime,
        available: this.props.available
    }
    console.log(this.state.available)
}

The value of my checkbox should be initialized based on the value of this.state.available, but every checkbox is checked when the component is rendered.

I'm looking at the value of this.state.available in two different places, and in both places, I get 5 trues and 2 falses.

Is there some aspect of the component life cycle that I'm missing here? Do I need to utilize something like getInitialState() (didn't change anything when I tried)?

Hoping this is something simple and stupid I overlooked since it seems like such basic functionality...




Aucun commentaire:

Enregistrer un commentaire