I have a list of items and I have a plus Icon next to each item. I am trying to add the item(which is passed down as prop from a parent component) into an array after clicking the plus Icon. So here is my onIconClick function:
state = { toggleIcon: "disabled", itemArray: [] };
onIconClick = () => {
const { item } = this.props;
const tempArray = this.state.itemArray.slice(0);
if (this.state.toggleIcon === "disabled") {
tempArray.push(item);
console.log("tempArray: " + tempArray.length);
console.log("tempArraySummary: " + tempArray);
this.setState({ toggleIcon: "enabled", itemArray: tempArray });
console.log("Here is the item array: " + this.state.itemArray);
} else {
this.setState({ toggleIcon: "disabled" });
console.log("Cancel Selected item");
}
};
...
...
// Applied Semantic-ui React here
return(
<Icon className={`${this.state.toggleIcon} plus`} onClick={this.onIconClick} />
);
So basically what I am doing here is to declare a temporary array, and push each item into the temporary array after the icon has been clicked, and then set the itemArray state to the temporary array.
When I tested this code, the first time I click on the icon, on the console, tempArray
added item successfully, but itemArray
is empty, but when I click the icon again to disable it, and click it again to add the item again, tempArray
now has 2 items in it, but itemArray
only has 1 item in it. I can't figure out why on the first time the page gets rendered, the item is not added into the itemArray