Building a Custom Rating Component in React

Introduction

In this digital world, giving a seamless & engaging user experience is required for all web applications. One way to improve the user experience is through Customer reviews, which allow users to share their feedback quickly.

In this article, I'll show how to create a custom rating component in React.

Step 1. We need to create a new React app.

npx create-react-app rating-demo

And, also you need to install the react-icons package to get the icons.

npm install react-icons

This command will create a new react app and the icons for our rating component. Then, open the React app in your favorite editor.

Step 2. Create a new file named Star.js under the src folder and add the following code.

import { FaStar } from "react-icons/fa";

function Star({ selected = false, onSelect }) {
    return <FaStar color={selected ? "red" : "grey"} onClick={onSelect}/>;
}

export default Star;

Step 3. After, we need to create a StarRating.js file that will utilize the Star component and add the following code in the file.

import Star from './Star';
import { useState } from 'react';

const createArray = (length) => [...Array(length)];

function StarRating({totalStars = 5}) {
    const [selectedStars, setSelectedStars] = useState(0);
    return (
        <>
            {createArray(totalStars).map((n, i) => <Star key={i} selected={selectedStars > i} onSelect = {() => setSelectedStars(i+1)}/>)}
            <p>{selectedStars} of {totalStars} stars</p>
        </>
    );
    
}

export default StarRating;

Now, we need to use the StarRating Component in the App.js file by removing the default and using the below code.

import logo from './logo.svg';
import './App.css';
import StarRating from './StarRating';

function App() {
  return (
    <StarRating totalStars={5} />
  );
}

export default App;

Finally, you can run the app from the command prompt using npm start and you can see the rating in our localhost.

Npm Start

Conclusion

You can change the number of stars by changing the value of the total star on the App.js. Based on this, we can see the changes in the app.