How To Create A Rating Component In React

Introduction

This article demonstrates how to create a rating component using reactjs. In this rating component, the user can select half as well as full rating that we select and display the selected value.

For this, we will use a npm package 'react rating'

Prerequisites

  • Basic knowledge of ReactJS
  • Visual Studio Code
  • Node and NPM installed

Rating Component in React

To achieve this we need to install a package 'react-rating' to implement the rating component in react and can import it and use it in our sample project.

Step 1 - Create a React.js Project

Let's create a new React project by using the following command.

npx create-react-app rating-app

Step 2 - Install NPM dependencies

npm i react-rating

Step 3 - Create a Component for rating

Create a folder and inside it create a component, 'ratingComponent.js'. Add the following code to this component.

import React, { useState } from "react";
import ReactStars from "react-rating-stars-component";
 
function RatingComponent() {
    const ratingExample = {
        size: 50,
        count: 5,
        color: "black",
        activeColor: "yellow",
        value: 0,
        a11y: true,
        isHalf: true,
        emptyIcon: <i className="far fa-star" />,
        halfIcon: <i className="fa fa-star-half-alt" />,
        filledIcon: <i className="fa fa-star" />
      };
  return (
    <div>
      <h3>Rating Component </h3>
      <ReactStars {...ratingExample} />
    </div>
  );
}
export default RatingComponent;

So in the above code, we can add a function inside react stars that can provide the number of features that react rating package can provide.

const ratingExample = {
    size: 50,
    count: 5,
    color: "black",
    activeColor: "yellow",
    value: 0,
    a11y: true,
    isHalf: true,
    emptyIcon: < i className = "far fa-star" / > ,
    halfIcon: < i className = "fa fa-star-half-alt" / > ,
    filledIcon: < i className = "fa fa-star" / >
};

In the above code, we can set the size of a star, its initial color, and its initial value. We can check the available features of the star rating component in this link.

Step 4

Add the below code in App.js file

import './App.css';
import RatingComponent from './rating/ratingComponent';

function App() {
  return (
    <RatingComponent/>
  );
}
export default App;

Step 5

We need to add a script for using font awesome in your index .html file inside head tag.

After adding the below script we can be able to use interactive font for stars in this article otherwise we can use the normal icons for stars.

 <script
    src="https://use.fontawesome.com/releases/v5.13.1/js/all.js"
    data-auto-replace-svg="nest"
  ></script>

Step 6 - Output

Now, run the project by using the 'npm start' command, and check the result.

How To Create A Rating Component In React

Summary

So in this article, we have discussed how we can create a rating component in reactjs.