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: A 5-star rating system provides a quick and intuitive way for users to express their opinions and preferences. It encourages user engagement by allowing them to easily provide feedback on products, services, or content.

Decision-Making Aid: For other users, the star ratings serve as a helpful reference when making decisions. They can quickly see the average rating and read reviews to determine the quality or popularity of items.

Improved User Experience: When implemented well, a 5-star rating system enhances the overall user experience. Users appreciate the simplicity and visual appeal of rating with stars, making it user-friendly and accessible.5 star rating in react.js

User-generated Content: Star ratings can generate user-generated content, such as reviews and comments, which can add value to your website or app. It fosters a sense of community and provides additional information to users.

5 star rating in react.js

Creating a 5-Star Rating System in React: To create a 5-star rating system in React, you can follow these steps:

  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 (e.g., changing to gold for a selected star).
  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, and useState is a React hook used for managing state within functional components.

Then defines a functional component named App. It’s exported as a named export, which means it can be imported and used in other parts of your application.

  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. It also defines 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

I am a software engineer with over 10 years of experience in blogging and web development. I have expertise in both front-end and back-end development, as well as database design, web security, and SEO.