Push checkbox value to array on state onChange

Connor G Roane picture Connor G Roane · Feb 15, 2018 · Viewed 7.8k times · Source

I want to allow users to select days of the week from checkboxes. When a checkbox is checked, the value of that checkbox should update this.state.days. Instead of adding to the array, it's simply overwriting this.state.days. Tried using simple spread operator, but I then get an error indicating that react cant convert null into object - this even happens when I set days to [1,2] so that it isn't undefined at the start. See change function below

this.state = {
    days:[]
}

handleDaySelect (event) {
    if (this.state.days) {
        var dayArr = [...this.state.days]
    } else {
        var dayArr = [];
    }
    dayArr.push(event.target.value)        
    this.setState({
        days: dayArr
    })
}

Render function:

render() {

    const daysOptions = ["Monday", "Tuesday", "Wednesday", "Thursday", 
    "Friday", "Saturday", "Sunday"].map((cur, ind) => {
        return (
            <div key={ind} className="checks" >
                <label>
                    <input type="checkbox" name={cur} value={cur} 
                    onChange={this.handleDaySelect} />{cur}
                </label>
            </div>
        )
    })
    return (
        <div id="newDeal" className="formContainer" >

            <div className="checkBoxContainer" >
                {daysOptions}
            </div>
        </div>
    )
}

Answer

Araz Babayev picture Araz Babayev · May 30, 2018
    handleDaySelect(event){
            let day_list = this.state.days;
            let check = event.target.checked;
            let checked_day = event.target.value;
            if(check){
                this.setState({
                    days: [...this.state.days, checked_day]
                })
            }else{ 
                var index = day_list.indexOf(checked_day);
                if (index > -1) {
                    day_list.splice(index, 1);
                    this.setState({
                        days: day_list
                    })
                } 
            }
        }

Hope this helps.