Skip to content

Instantly share code, notes, and snippets.

@Palayoub
Created December 30, 2022 10:31
Show Gist options
  • Save Palayoub/828f28791ea17f98b2aed92284c14fb9 to your computer and use it in GitHub Desktop.
Save Palayoub/828f28791ea17f98b2aed92284c14fb9 to your computer and use it in GitHub Desktop.
/**
Task 1: In the Vote box, add a downvote button to the right of Upvote.
Task 2: The number in the red box indicates the number of total vote received. It should be incremented by 1 when Upvote is pressed and decremented by 1 when downvote is pressed.
Task 3: Each button will remain in the pressed position after it is clicked. If it is clicked again, the vote will be canceled. For instance, if Upvote is clicked, then the total vote is 1, but if Upvote is clicked again, total vote becomes 0. Only one button can remain in the pressed position. For instance, if Upvote is pressed down and the vote is 1, when Downvote is clicked, Upvote will automatically bounce and Downvote will be pressed down. Total vote changes from 1 to -1. This guarantess that the vote can only have 3 possible values: -1, 0, and 1
**/
function Vote({ handleVotePress }) {
return (
<>
<div>Vote</div>
<button onClick={handleVotePress(1)}>Upvote</button>
<button onClick={handleVotePress(-1)}>Downvote</button>
</>
);
}
function Credit() {
const [value, setValue] = React.useState(0);
const handleVotePress = (vote) => () => {
//we judge if button is already pressed by the value of the total votes
const upVoteIsPressed = value === 1;
const downVoteIsPressed = value === -1;
//if button is pressed while vote already is -1 or 1, set the incoming vote value
if((upVoteIsPressed && vote === -1) || (downVoteIsPressed && vote === 1)) {
setValue(vote);
}
//cancel vote if upvote or down vote already pressed
else if(upVoteIsPressed || downVoteIsPressed) {
setValue(0);
}
else {
//normal bahaviour to increment or decrement the value of the vote
setValue(prevState => prevState + vote)
}
};
return (
<>
<div className="wrapper">
<div>Total vote received:</div>
<div className="box-wrapper">{value}</div>
</div>
<div className="wrapper">
<Vote handleVotePress={handleVotePress} />
</div>
</>
);
}
ReactDOM.render(<Credit />, document.getElementById("root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment