React component for creating Rating stars

Creating a 5-star rating system in a React component is important for various reasons, especially when you want to gather user feedback or allow users to rate products, services, or content on your website or application.

Here’s why it’s important and how to create such a system in React:

  • User Engagement and Feedback
  • Decision-Making Aid
  • Improves User Experience

How to Creat a 5-Star Rating System in React:

To create a 5-star rating system in React, you can follow these steps:5 star rating in react.js

  1. State Management: Use React’s state management (e.g., useState hook) to keep track of the current rating.
  2. Event Handling: Implement event handlers for hovering over stars and clicking on stars. These handlers will update the state to reflect the user’s interactions.
  3. Rendering: Generate the star elements dynamically based on the current rating. Use CSS classes to style the stars, highlighting the selected ones.
  4. Display: Display the current rating and the star elements in your React component, making sure to provide clear feedback to the user about their interactions.
  5. Styling: Define CSS styles to customize the appearance of the stars, including the color change for selected stars.
  6. Accessibility: Ensure your rating system is accessible by providing appropriate ARIA attributes and labels for screen readers.

import React, { useState } from 'react';
export function App(props) {
  const [rating, setRating] = useState(0);

  const handleStarHover = (event) => {
    const selectedRating = parseInt(event.target.getAttribute('rating'), 10);
    setRating(selectedRating);
  };
  const handleStarClick = (event) => {
    const selectedRating = parseInt(event.target.getAttribute('rating'), 10);
    setRating(selectedRating);
  };
  const renderStars = () => {
    const stars = [];
    for (let i = 1; i <= 5; i++) {
      const starClassName = i <= rating ? 'goldstar' : '';
      stars.push(
        <li
          key={`star-${i}`}
          rating={i}
          className={starClassName}
          onMouseEnter={handleStarHover}
          onMouseLeave={() => setRating(0)}
          onClick={handleStarClick}
        >
          ★
        </li>
      );
    }
    return stars;
  };
  return (
    <div>
      Rating: <span id="rating">{rating}</span>
      <ul id="stars">
        {renderStars()}
      </ul>
      <style>
        {`
          .goldstar {
            color: gold;
          }
          #stars li {
            display: inline;
            cursor: pointer;
          }
        `}
      </style>
    </div>
  );
}

Let’s break down the provided React code step by step and explain each part:

  1. Import Statements and Functional Component Definition:
import React, { useState } from 'react';
export function App(props) {

Here, we import the necessary modules. React is required for creating React components for react version below 17, and useState is a React hook used for managing state within functional components.

Then define a functional component named App.

  1. State Initialization and Event Handlers – handleStarHover and handleStarClick:
const [rating, setRating] = useState(0);
const handleStarHover = (event) => {
    const selectedRating = parseInt(event.target.getAttribute('rating'), 10);
    setRating(selectedRating);
};
const handleStarClick = (event) => {
    const selectedRating = parseInt(event.target.getAttribute('rating'), 10);
    setRating(selectedRating);
};

Initialize the state variable rating with an initial value of 0. Also define a state updater function setRating that will be used to update the rating state.

handleStarHover and handleStarClick handles user interactions with the stars. handleStarHover is triggered when a user hovers over a star, and handleStarClick is triggered when a user clicks on a star. They extract the rating attribute from the clicked or hovered star and update the rating state accordingly.

  1. Generating Star Elements – renderStars Function:
const renderStars = () => {
    const stars = [];
    for (let i = 1; i <= 5; i++) {
        const starClassName = i <= rating ? 'goldstar' : '';
        stars.push(
            <li
                key={`star-${i}`}
                rating={i}
                className={starClassName}
                onMouseEnter={handleStarHover}
                onMouseLeave={() => setRating(0)}
                onClick={handleStarClick}
            >
                ★
            </li>
        );
    }
    return stars;
};

This function dynamically generates the HTML for the 5-star rating display. It iterates through a loop from 1 to 5 and creates <li> elements for each star. It assigns a rating attribute to each star (values from 1 to 5) and applies the goldstar CSS class to stars that are less than or equal to the current rating. It also sets up event handlers for hovering and clicking on the stars.

  1. Finally render the starts using JSX
return (
    <div>
        Rating: <span id="rating">{rating}</span>
        <ul id="stars">
            {renderStars()}
        </ul>
        <style>
            {`
                .goldstar {
                    color: gold;
                }
                #stars li {
                    display: inline;
                    cursor: pointer;
                }
            `}
        </style>
    </div>
);

This part of the code renders the JSX (React elements) to display the rating system. It includes a <div> containing the current rating, an unordered list (<ul>) where the stars are generated by the renderStars function, and inline CSS styles that define the appearance of the stars and the goldstar class.

Written by

With 10+ years in software engineering, I specialize in blogging and web development. My skills span front-end, back-end, database design, web security, and SEO. Passionate about crafting helpful digital experiences.