Reputation: 10947
I would like to add an item to the state.contacts array when a checkbox is checked, and remove the item when a checkbox is unchecked. How would I do this in react?
Currently using a pub/ sub pattern and callbacks:
My component renders using:
handler: function(e) {
channel.publish({
channel: "contact",
topic: "selectedContact",
data: {
id: e.target.attributes['data-ref'].value
}
});
},
return (
<div className="selector">
<input type="checkbox"
checked={isSelected} data-ref={id}
onClick={this.handler} />
</div>
);
My click handler:
componentDidMount: function() {
var page = this;
this.loadContacts();
// setup subscribe
contactChannel.subscribe("selectedContact", function (data, envelope) {
page.handleSelectedContact(data.id, page);
});
},
handleSelectedContact: function(id, page) {
var page = this;
var callback = function () {
var arrayPush = [];
var arrayPush = page.state.selected.slice();
var index = page.state.selected.indexOf(id);
if (index === -1) {
// if no id in array, push it
arrayPush.push(id);
page.setState({selected: arrayPush})
var idAsNumber = parseInt(id);
// show selected value in checkbox
var newContacts = page.state.contacts.map(function (contact) {
if (contact.id === idAsNumber) {
contact.isSelected = true;
}
return contact;
});
} else {
// remove id from array
page.state.selected.splice(index, 1);
page.setState({selected: arrayPush})
}
// set new contacts state
page.setState({contacts: newContacts});
console.log(page.state.selectedContacts);
basketChannel.publish({
channel: "basket",
topic: "addContactToBasket",
data: {
id: id,
newTotal: arrayPush.length
}
});
}
BasketService.addPerson(id, callback);
},
Upvotes: 0
Views: 2304
Reputation: 1802
To add an element to an array when clicking a checkbox in React, you just add an event handler attribute to the JSX tag, add a ref attribute to the elements you want to access for getting values, and then push an item to the state:
getInitialState: function() {
return {isSelected: false, items: []};
},
handler: function(e) {
var isSelected = !this.state.isSelected,
items = this.state.items.push(e.target.value);
this.setState({isSelected: isSelected, items: items});
},
render: function() {
return (
<div className="selector">
<input type="checkbox"
checked={this.state.isSelected}
onChange={this.handler} />
</div>);
Upvotes: 1