In this blog we will descuss how we can create our own rating component using tailwindcss.
Lets start by installing some dependencies we need to get started, assuming you have tailwindcss installed before you read this blog, you need to install react-icons
for the icons
npm install react-icons
Now that we installed all the dependencies we can start coding our component. We will make the component take user input for the stars and show it, for example:
js<Rating stars={4} maxStars={5} />
So the component takes how many stars given and how many stars are max.
Inside the component the logic is we have to know how many stars to color golden and how many stars to keep gray. So we will make 2 arrays, one for gold color and one gray
jsconst goldStars = [...new Array(stars).fill(1)]
const grayStars = [...new Array(maxStars - stars).fill(0)] // if we substract stars from max stars we get how much left
const allStars = [...goldStars, ...grayStars] // combining 2 arrays into one
in the upper code we made 2 arrays, filled the first array with 1 and second with 0 so we can do some conditional rendering, then we are combining those 2 arrays. Now we have to render the stars
js{allStars.map((item, index) =>
item == 1 ? (
<AiFillStar className="text-yellow-500" />
) : (
<AiOutlineStar />
)
)}
in this code while mapping the allStars array we are conditionally returning an star icon component from react-icons
now if we glue all the code togather in a component we get a nice looking rating component
jsimport React from "react";
import { AiFillStar, AiOutlineStar } from "react-icons/ai";
const Rating = ({ stars, maxStars = 5 }) => {
const goldStars = [...new Array(stars).fill(1)]
const grayStars = [...new Array(maxStars - stars).fill(0)]
const allStars = [...goldStars, ...grayStars]
return (
<div className="flex items-center">
{allStars.map((item, index) =>
item == 1 ? (
<AiFillStar className="text-yellow-500" />
) : (
<AiOutlineStar onClick={() => setCount(index + 1)} />
)
)}
</div>
);
};
export default Rating;
Copythight © All Rights Reserved.