I need to change the icon color according to the movie rating. I made a function that receives the value of the classification and returns a value for the className inside the svg. However, all icons turn red. Someone help me to solve this problem.
Conditions for changing color.
Rating: 0 to 100
0 - white
20 or 40 - red
60 - orange
80 or 100 - green
//Punctuation/Note
const setVote = (note) => {
console.log("NOTE", note);
if (note === 0) { // 0
return "white";
} else if (note >= 20 || note <= 40) {
return "red";
} else if (note === 60) {
return "orange";
} else return "green";
};
<div className='box-note'>
<span className='rating'>{rating}</span>
<i className='icon-vote-like'>
<svg id="Icon_Thumbs_Up_Filled" data-name="Icon / Thumbs Up / Filled" xmlns="http://www.w3.org/2000/svg" width="17" height="17" viewBox="0 0 17 17">
<rect id="Box" width="17" height="17" fill="none" />
<path id="Path_1994" fill="#6cbe61" className={setVote(rating)} data-name="Path 1994" d="M97-8.286h2.805v-8.229H97Zm15.429-7.543a1.391,1.391,0,0,0-1.4-1.371H106.6l.666-3.134.021-.219a1.021,1.021,0,0,0-.309-.727l-.743-.72-4.615,4.519a1.326,1.326,0,0,0-.414.967v6.857a1.391,1.391,0,0,0,1.4,1.371h6.312a1.394,1.394,0,0,0,1.29-.837l2.118-4.834a1.328,1.328,0,0,0,.1-.5v-1.31l-.007-.007Z" transform="translate(-96.143 23.714)" />
</svg>
</i>
</div>
CSS
.white {
fill: #ffffff;
}
.orange {
fill: #ffa500;
}
.green {
fill: #008000;
}
.red {
fill: #ff0000;
}
CodePudding user response:
You have wrong condition here:
else if (note >= 20 || note <= 40) {
return "red";
instead of ||
should be &&
.
But if you want to implement ranges, you should also correct other conditions:
const setVote = (note) => {
console.log("NOTE", note);
if (note <20) { // 0-19
return "white";
} else if (note >= 20 && note <= 40) { // 20-40
return "red";
} else if (note > 40 && note <= 60) { // 41-60
return "orange";
} else return "green"; // 60
};
CodePudding user response:
This should work:
const setVote = (note) => {
console.log("NOTE", note);
if (note === 0) { // 0
return "white";
} else if (note >= 20 && note <= 40) {
return "red";
} else if (note === 60) {
return "orange";
} else return "green";
};
Better with interval:
const setVote = (note) => {
console.log("NOTE", note);
if (note < 20) { // 0
return "white";
} else if (note >= 20 && note <= 40) {
return "red";
} else if (note >= 40 && note <= 60) {
return "orange";
} else return "green";
};
The idea is to use AND instead of OR
CodePudding user response:
I found the error, it should be ===. Look:
const setVote = (note) => {
console.log("NOTE", note);
if (note === 0) {
return "white";
} else if (note === 20 || note === 40) {
return "red";
} else if (note === 60) {
return "orange";
} else return "green";
};