I am a novice who's doing the project in React. What I am trying to do here is that I am trying to draw circles 1~5 to display the values from JSON data.
JSON data value receives from -1 to 9 if the certain key's value is -1, then that specific key should not be displayed with circles.
if the certain key's value is at least 0 or >= 0, then 0 would be 5 non-colored circles.
if the certain key's value is 9 then there would be 4 fully colored circles and one half-colored circle.
I've been stuck on this problem for 4 days now...
{
"result" : {
"product_id" : 1
"product_name" : "apple"
"rating" : {
"rating1" : -1,
"rating2" : 4,
"rating3" : 9,
"rating4" : 2,
"rating5" : -1
}
}
}
the JSON data looks like above
and here is the circles I got
const FullCircleRating = styled.div`
background: grey;
border-radius: 100%;
display: inline-block;
height: 15px;
width: 15px;
overflow: hidden;
position: relative;
&::after {
content: "";
position: absolute;
display: block;
height: 100%;
left: 0;
background: orange;
width: ${(props) => props.circles.full};
}
`;
const HalfCircleRating = styled.div`
background: grey;
border-radius: 100%;
//display:inline-block;
height: 15px;
width: 15px;
overflow: hidden;
position: relative;
&::after {
content: "";
position: absolute;
//display:block;
height: 100%;
left: 0;
background: orange;
width: 50%;
}
`;
const circlesValue = {
full: "100%",
half: "50%",
};
const Circles = styled.div`
display: flex !important;
`;
const CircleRating = styled.div`
background: grey;
border-radius: 100%;
//display:inline-block;
height: 15px;
width: 15px;
overflow: hidden;
position: relative;
&::after {
content: "";
position: absolute;
//display:block;
height: 100%;
left: 0;
background: orange;
}
`;
I used styled-components
and I was trying to draw through mapping out the circles first but don't really get how I could display the right number of circles based on the JSON data value I receive.
{[2,4,6,8,10].map(index => {
return (
<Circles><FullCircleRating index={index} /></Circles>
)
})}
this is how I at first tried to display 5 circles.
If you need more information on the codes.
You could achieve it by calculating the number of circles fully colored with orange, one half colored, and the remaining grey colored.
The fully colored will be the rating divided by two and rounded down
Math.floor(rating / 2)
For the half colored need to check if the rating is odd with the mod operator
rating % 2 !== 0
For the grey colored ones, do the same calc as for the orange but with the difference of the max (10) minus the rating rounded down
Math.floor((10 - rating) / 2)
Then do some wrangling to generate the arrays of elements.
const fullCircles = Array.from({ length: fullCirclesCount }, () => (
<FullCircleRating />
));
const emptyCircles = Array.from({ length: emptyCirclesCount }, () => (
<CircleRating />
));
if (rating % 2 !== 0) fullCircles.push(<HalfCircleRating />);
return <div>{[...fullCircles, ...emptyCircles]}</div>;