Skip to content
Related Articles

Related Articles

How to create a rating component in ReactJS ?
  • Difficulty Level : Medium
  • Last Updated : 03 Mar, 2021
GeeksforGeeks - Summer Carnival Banner

The following approach covers how to create a rating component in React JS.

Prerequisite:

  • Basic knowledge of npm & create-react-app command.
  • Basic Knowledge of styled-components.
  • Basic Knowledge of useState() React hooks.

Basic Setup: You will start a new project using create-react-app command:

npx create-react-app react-rating

Now go to your react-rating folder by typing the given command in the terminal.

cd react-rating

Required module: Install the dependencies required in this project by typing the given command in the terminal.



npm install --save styled-components
npm install --save react-icons

Now create the components folder in src then go to the components folder and create two files Rating.js and RatingStyles.js.

Project Structure: The file structure in the project will look like this.

Example: In this example, we will design a rating component, for that we will need to manipulate the App.js file and other created components file.

We create a state with the first element rate as an initial state having a value of 0 and the second element as function setRate() for updating the state. Index numbers ranging from 0 to 4 are assigned with an addition of 1 to the newly initialized variable givenRating . While mapping the array using Map() method, we associate the value of givenRating variable with each of the five radio buttons (for example, 1 for the first button and so on).

We update the value of the state with the help of onClick function which sets its value equal to givenRating whenever it is called. For example, if we click on the 4th star (from left), we know the value of givenRating associated with this star (or radio button) is 4. This value of 4 gets assigned to our state. Now the role of the conditional operator comes into play. Only those radio buttons get selected (or change their color) which have a value equal to or less than 4. So as a result, we get a four-star rating.

Rating.js




import React, { useState } from "react";
import { FaStar } from "react-icons/fa";
import { Container, Radio, Rating } from "./RatingStyles";
const Rate = () => {
  const [rate, setRate] = useState(0);
  return (
    <Container>
      {[...Array(5)].map((item, index) => {
        const givenRating = index + 1;
        return (
          <label>
            <Radio
              type="radio"
              value={givenRating}
              onClick={() => {
                setRate(givenRating);
                alert(`Are you sure you want to give ${givenRating} stars ?`);
              }}
            />
            <Rating>
              <FaStar
                color={
                  givenRating < rate || givenRating === rate
                    ? "000"
                    : "rgb(192,192,192)"
                }
              />
            </Rating>
          </label>
        );
      })}
    </Container>
  );
};
  
export default Rate;

RatingStyles.js




import styled from 'styled-components';
  
export const Container = styled.div`
   display: flex;
   justify-content: center;
   align-items: center;
   min-height: 60vh;
   font-size: 60px;
`
export const Radio = styled.input`
   display: none;
`
export const Rating = styled.div`
   cursor: pointer;
`

App.js




import './App.css';
import Rating from './components/Rating';
  
function App() {
  return (
     <Rating />
  );
}
  
export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:


Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :