Home > Blockchain >  How to control a dynamic checkbox in reactjs
How to control a dynamic checkbox in reactjs

Time:09-29

I have 2 arrays say Array1 and Array2. Where Array2 is some subset of Array1. Now I am creating checkbox of all the items present in array1 and I want the ones to be checked which are present in array2. I hope you understand my problem and suggest me what I can do.

CodePudding user response:

You may try the following snippet,

return (
    <div className="list">
        <div className="title">Your Checklist Items:</div>
        <div className="list-container">
            {array1.map((item, index) => (
                <div key={index}>
                    <input
                        value={item}
                        type="checkbox"
                        checked={array2.includes(item) ? "checked" : "unchecked"}
                    />
                    <span>{item}</span>
                </div>
            ))}
        </div>
    </div>
);

CodePudding user response:

Firstly you need a state holding two arrays (or at least one, that will be controled by checkboxes).

this.state = {
    a: [11,22,33,44,55,66,77,88,99],
    b: [22,44,66,88],
}

Secondly you need handler for change of that array when checkbox is changed.

handleChange(e, number) {
    this.setState(prevState => {
        const index = prevState.b.indexOf(number);
        if(index >= 0){     
            prevState.b.splice(index, 1);
        } else {
            prevState.b.push(number)
        }
        return { b: prevState.b }
    })
}

Lastly you need to render checkboxes and control them with state.

render() {
    return(
        <div>
            {this.state.a.map((item, index) => (
                <div key={ index }>
                    {item   " "}
                    <input
                        checked = { this.state.b.includes(item) }
                        onChange = { e => { this.handleChange(e, item) } } 
                        type = "checkbox"
                        />
                </div>
            ))}
        </div>
    )}
}

Full demo here: http://jsfiddle.net/nogare/76spduct/

  • Related