Publish a star rating system in your React project

Are you looking to take a number value from your data set and turn it into a traditional star rating system?

You can see this in practice on the "Bookshelf" section of this website's home page. The feature is reading a list of books stored in a Fauna database, pulling each book's number rating (ranging from 1 to 5), and then converting that number to stars using JavaScript.

Here's the approach I took in three steps:

1. Get your icons

Snag the React Icons package, which gives you a bunch of icon options from Font Awesome, Material Design and Bootstrap, including half stars, unfilled stars, etc. Import the star(s) you want to use in your project.

import { BsStarFill } from "@react-icons/all-files/bs/BsStarFill"

2. Write your component

What's the best way to create the appropriate number of stars based on a number value in our database? Enter this StackOverflow answer, which doesn't just deliver one solution, but three ways of doing it:

We're going to feed our rating component the number of stars in the props (that number exists at props.rating below):

function BookRating(props) {
    return Array.apply(null, { length: props.rating }).map((e, i) => (
        <BsStarFill />

3. Call your component

Now we have a component that will return the number of stars it's given, so we just call the component inside our forEach loop and feed it that number, which in my case lives at book.status.rating:

   <BookRating rating={book.status.rating} />

If the number in your data set is 5, you'll get five instances of your icon.


Copyright 2021 Ian Forrest Web Development.