class App extends React.Component {
constructor(props) {
super(props);
this.state = {
emojis: [
{ id: 1, emoji: '🚀', count: 0, },
{ id: 2, emoji: '☺', count: 0, },
{ id: 3, emoji: '☻', count: 0, },
],
showResults: false,
winningEmoji: null,
}
this.handleVote = this.handleVote.bind(this);
this.handleShowResult = this.handleShowResult.bind(this);
}
handleVote(id) {
this.setState(state => {
const { emojis } = state;
const updateEmojis = emojis.map(emoji => {
if (emoji.id === id) {
return {
...emojis, count: emoji.count + 1
}
}
return emoji;
})
return {
emojis: updateEmojis,
}
})
}
handleShowResult() {
this.setState(state => {
const winningEmoji = state.emojis.reduce((previousValue, currentValue) => {
return previousValue.count > currentValue.count ? previousValue : currentValue;
});
console.log(winningEmoji);
return {
showResults: true,
winningEmoji,
}
})
}
render() {
const { emojis, showResults, winningEmoji } = this.state;
return (
<div>
<ul>
{
emojis.map(emoji =>
<li key={emoji.id}>
{emoji.emoji} - {emoji.count}
<button onClick={() => this.handleVote(emoji.id)}>Vote</button>
</li>
)
}
</ul>
<button onClick={this.handleShowResult}>Show Result</button>
{
showResults && (
<div>
<h3>Winning Emoji:</h3>
{
winningEmoji && <div>{winningEmoji.emoji} - {winningEmoji.count}</div>
}
</div>
)
}
</div>
)
}
}