Reputation: 3357
I'm working with a custom Library in React, where you can add emojis, And I'm trying to make a counter variable to the object, which increases each time a user clicks on it.
The point is to make it into an array, of several emojis, but so far, I'm trying to make it work with only one.
So I have a condition rather the emoji should be shown or not
{
this.state.showEmoji &&
<div className="emoji">
<Emoji
onClick={this.increment}
emoji={{ id: this.state.emoji.id, skin: 1, }}
size={25}
/>
<p>{this.state.emoji.count}</p>
</div>
}
Inside I render my Emoji along with the counter, which determinates how many times the emoji has been rendered/clicked
I'm not sure if I should make an anonymous function or make a handler, I tried out with the handler
I have made a custom emoji object in my state (which will eventually be an array of emoji objects)
emoji: {
id: '',
count: 0,
}
Along with my increment handler method:
increment = (emoji) =>{
console.log(emoji.id);
console.log(this.state.emoji.id);
this.setState({
count: this.state.emoji[emoji.id].count++
});
}
I successfully console log the emoji objects state id and then passed in emoji object, and they match.
But when I try to mutate the state I get this error:
TypeError: Cannot read property 'count' of undefined
Why can't I access the object with the id in this case?
Upvotes: 0
Views: 136
Reputation: 2210
Please take a look at this sandbox code, it may help with managing the array of emojis as well.
Upvotes: 0
Reputation: 2938
increment = (emoji) =>{
const { emoji } = this.state; // isn't that more readable?
const _emoji = {
...emoji,
count: emoji.count + 1
} //this will create a copy of your emoji object.
// use +1 instead of ++ to make sure you are keeping the original count value as it is, 'PURE PROGRAMMING'
this.setState({ emoji: _emoji });
}
Upvotes: 2