I need to track the set of items a user selects. I initialized the component's state to contain an array to hold the set of data-ids the user clicks.
Each item contains an "onClick" listener and a data-id attribute with a value:
<div onClick={this.selectItem} data-id={this.props.id}>Select this item</div>
My class and method:
class Item extends React.Component {
constructor() {
super();
this.selectItem = this.selectItem.bind(this);
this.state = {
itemsSelected: []
};
}
selectItem(e) {
const id = e.target.dataset.id;
// copy state to new array with the new value
let itemsSelected = [...this.state.itemsSelected, id];
// Set state and display it, after update occurred
this.setState({ itemsSelected }, function() {
console.log('itemsSelected: ', this.state.itemsSelected);
});
}
I would expect the console log to display a growing set of ids as items are clicked, however it displays only the last item clicked (array length is always 1). YET, if the same item is clicked, the array grows.
So, clicking item 1, then 2, then 3 results in the state being set with an array of one value of 3. And clicking item 1 three times results in an array of 3 values, each being the value of 1.
I want the array to contain the ids of any/all items the user clicks.
Project dependencies:
"dependencies": { "history": "4.2.0", "re-base": "2.2.0", "react": "15.3.2", "react-addons-css-transition-group": "15.3.2", "react-dom": "15.3.2", "react-router": "4.0.0-alpha.4" },