I want to be able to make a dynamic card component that will eventialy call an api to get the data. Right now I will be using dummy data.
I want a name, description and star rating for each card. What I am not to sure about is how I would get the star images in each card component.
export const ReviewCards: React.FC<ReviewCardsProps> = ({ name, star, description }) => {
return (
<>
<Card className="reviewCards sm:h-415">
<CardContent>
<div className="flex p-4 justify-between">
<p className="text-lg">{name}</p>
<div className="flex w-3.5 space-x-1.5 justify-end">
<img src={StarIcon} alt="Ratings icon" />
<img src={StarIcon} alt="Ratings icon" />
<img src={StarIcon} alt="Ratings icon" />
<img src={StarIcon} alt="Ratings icon" />
<img src={EmptyStar} alt="Ratings icon" />
</div>
</div>
<p className="text-sm font-extralight p-7">{description}</p>
</CardContent>
</Card>
)
}
I dont want to manually put in the images. I want to be able to say
<div className="flex w-3.5 space-x-1.5 justify-end">{star}<div>
And then when calling the component I want to be able to say:
<ReviewCard name="Bianca", star={4} description={...} /
CodePudding user response:
You can create a array and assign the images accordingly..
// Array index starts with 0, so added 1 to the index
const HelperStar = (index) =>
index 1 < star ? StarIcon : index 1 - 0.5 === star ? HalfStar : EmptyStar;
const imageSource = new Array(5)
.fill(0)
.map((data, index) => HelperStar(index);
return (
// ...
<div className="flex w-3.5 space-x-1.5 justify-end">
{imageSource.map((data) => <img src={data} alt="Ratings icon" />}
</div>
</div>
//..
);