-
-
Save amariliscamargo/bd80947080d3bd2cfca0039be3759576 to your computer and use it in GitHub Desktop.
like-dislike buttons. Created with create-react-app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
import "./App.css"; | |
const reduceOne = (prevState, groupName, otherGroupName) => { | |
prevState[groupName].wasClicked | |
? prevState[groupName].count = prevState[groupName].count - 1 | |
: prevState[groupName].count = prevState[groupName].count + 1; | |
prevState[groupName].wasClicked = !prevState[groupName].wasClicked; | |
if (prevState[otherGroupName].wasClicked) { | |
prevState[otherGroupName].count = prevState[otherGroupName].count - 1; | |
prevState[otherGroupName].wasClicked = false; | |
} | |
return prevState; | |
}; | |
const reducer = action => | |
(prevState, props) => | |
action.type === "TOGGLE_LIKE" | |
? reduceOne(prevState, "like", "dislike") | |
: reduceOne(prevState, "dislike", "like"); | |
class App extends Component { | |
state = { | |
like: { | |
count: 0, | |
wasClicked: false, | |
}, | |
dislike: { | |
count: 0, | |
wasClicked: false, | |
}, | |
}; | |
toggleLike = () => this.setState(reducer({ type: "TOGGLE_LIKE" })); | |
toggleDislike = () => this.setState(reducer({ type: "TOGGLE_DISLIKE" })); | |
render() { | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<h1 className="App-title">Like - Dislike</h1> | |
</header> | |
<p className="App-intro"> | |
<button className="like-button" onClick={this.toggleLike}> | |
Like | {this.state.like.count} | |
</button> | |
<button className="dislike-button" onClick={this.toggleDislike}> | |
Dislike | {this.state.dislike.count} | |
</button> | |
</p> | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment