24
rated 0 times
[
25]
[
1]
/ answers: 1 / hits: 20185
/ 7 Years ago, sat, december 23, 2017, 12:00:00
I tried to control dynamic checkbox rendered from my array. My problem is i have multiple checkbox but i only have one state in my constructor. Is there any others method on how to control dynamic fields/items without
Below is my code :
onAddingItem = (item) =>{
var self = this;
const value = item.target.type === 'checkbox' ? item.target.checked : item.target.value;
var newArray = self.state.product.slice();
if(item.target.checked){
newArray.push(item.target.value);
self.setState({addProducts:value, product:newArray})
} else {
newArray.splice(item.target.value, 1); //remove element
self.setState({addProducts:value, product:newArray}); //update state
}
}
render(){
var self = this;
const {title, photo, photoHeight, photoWidth, showPhoto, editorState, description, editorData, productsList} = this.state;
const product_list = productsList.map((index, i) =>
<tr key={i+1}>
<td>{i+1}</td>
<td>{index.name}</td>
<td>
<div class=checkbox checkbox-circle checkbox-color-scheme>
<label class=checkbox-checked>
<input type=checkbox value={index.name} checked={self.state.addProducts} onChange={this.onAddingItem}/> <span class=label-text>Add ?</span>
</label>
</div>
</td>
</tr>
);
Whenever i checked one of the checkbox. All the other checkbox also being checked. As you see i want to add the value of the checkbox into an array when its checked and remove the existing value from array when the checkbox is unchecked.
More From » reactjs