Issue
I've been running into a problem with my react web application. In want to make a voting system where if you hit the like button it changes color and it can only be liked once. If you hit it again it goes back to 'neutral' and the like count gets decremented. Same goes for the dislike button. If you have something liked and you hit the dislike, for example, the the like goes back to eutral and the dislike changes color. Basically like the YouTube video like system. Im running into this problem, though, with my method:
const[score,setScore] = useState(0);
const[dislike,setDislike] = useState(0);
const[buttonState,setButtonState] = useState(true);
var boolD = true;
var boolL = true;
const incrmentLike = () => {
setScore(idea.score +=1)
console.log(idea.score)
}
var disliked = false;
const incrmentDislike = () => {
setDislike(idea.dislike +=1)
}
var flag = 0;
function toggleDislike(){
if(flag===0){
console.log(flag)
flag=1;
incrmentDislike()
console.log(flag)
disliked = true;
}
else if(flag===1){
setDislike(idea.dislike -=1)
disliked = false;
flag=0;
console.log(flag)
}
}
return(
<div className="idea-details">
{isPending && <div>Leading...</div>}
{idea && (
<article>
<h2>{idea.ideaTitle}</h2>
<p>Written by {idea.author}</p>
<div>{idea.body} </div>
<div>{idea.score} Likes {idea.dislike} Dislikes</div>
</article>
)}
<a type="button" className={classNameLU} id="button2" title="button" onClick={() => incrmentLike()}>Like!</a>
<div
className="btn btn-warning btn-lg"
style={{ backgroundColor: dislike ? "#35b5f1" : "#8b8b8b" }}
id="toggleDiv"
onClick={toggleDislike}
>
Dislike
</div>
</div>
);
} Basically The flag always gets reset to 0 and the method never gets to the if statement where the flag == 1. I think its because useState() is reseting the variable somehow. I was wondering if I could get help to get around this? I'm only working on the dislike button right now. setScore is the like button. You can ignore the first button.
Solution
React and jquery don't generally mix. The issue is that jquery directly manipulates the DOM outside the React component lifecycle so React isn't triggered to rerender the UI. Additionally, yes, flag is reset to 0 each render cycle, it's not held in any state or React ref so it's value isn't saved from render to render. Stick to using React state to persist values from render to render.
Move the background color to a style prop and use the dislike state to conditionally set one background color or the other.
<div
className="btn btn-warning btn-lg"
style={{ backgroundColor: disliked ? "#35b5f1" : "#8b8b8b" }}
id="toggleDiv"
onClick={toggleDislike}
>
Dislike
</div>
Answered By - Drew Reese
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.