jack
jack

Reputation: 81

react js input checkbox toggle value

Hear constructor of react js component

constructor(props) {
    super(props);
    this.state = {
        array : []
    }
    this.displayPageView = this.displayPageView.bind(this);
    this.onChange = this.onChange.bind(this);
}

Hear on Chnage function when click on check box push that value in state array

onChange(e) {
    console.log("e.target.name >>",e.target.name)
    console.log("e.target.value >>",e.target.value);
    remove(this.state.array,{ [e.target.name] : !parseInt(e.target.value) })
    this.state.array.push({ [e.target.name] : !parseInt(e.target.value) });
    console.log("array >>",this.state.array)
    //this.setState({ [e.target.name] : e.target.value });
}

Hear load check box view

displayPageView(){
    const id = parseInt(this.props.params.id);
    const memberships = find(this.props.currentPageData.data.memberships,{ id : id });
    const accessKey = JSON.parse(memberships.access_key);
    console.log("accessKey >>",accessKey);
    return map(accessKey, (value,key) =>(
        <div className="form-group col-sm-2" key={key}>
            {ucfirst(key)}
            {
                map(value, (value2,key2) =>(
                    <div className="checkbox" key={key+"_"+key2}>
                        <label key={key+"_"+key2}>
                            <input type='checkbox' key={key+"_"+key2} ref={value2} name={key+"_"+key2} value={value2} checked={(parseInt(value2)) ? true : false } onChange={this.onChange}></input>
                            {(key2=='index') ? 'List' : ucfirst(key2)}
                        </label>
                    </div>
                ))
            }
        </div>
    ));
}

When i click on check box push that name and value in array state object form and i also want to change check box checked value (true/false).

Upvotes: 0

Views: 1743

Answers (1)

Dane
Dane

Reputation: 9542

Don't mutate the state directly, instead use setState():

onChange(e) {
    let newArray = this.state.array.slice();
    remove(newArray, { [e.target.name] : !parseInt(e.target.value) });
    this.setState({
      array: newArray.concat({ [e.target.name] : !parseInt(e.target.value) })
    });
}

Once your state update occurs correctly, the checkboxes also ought to display appropriately.
Update: I've created a pen for you: codepen.io/danegit/pen/YEWYjx?editors=1010 Check it out and play with it. You can see that the value of state is bound to the checkbox

Upvotes: 1

Related Questions