DEV Community

Cover image for Creating a Dynamic Star Rating System in React
Kartik Budhraja
Kartik Budhraja

Posted on • Edited on

Creating a Dynamic Star Rating System in React

When it comes to user feedback, star ratings have become a ubiquitous and intuitive way for people to express their opinions. In this article, we'll walk through the process of creating a dynamic star rating system using React. This interactive component allows users to easily rate something using a star-based system, and even lets them decide how many stars they want to display.

Follow for more - Linkedin

Setting Up the Basics

Firstly, let's import the necessary styles and React dependencies to get started:

In this snippet, we import the required CSS file for styling and React along with the useState hook for managing state in functional components.

import "./styles.css";
import React, { useState } from "react";
Enter fullscreen mode Exit fullscreen mode

State Management

We use the useState hook to manage three pieces of state: rating (to store the user's selected rating), hover (to track the currently hovered star), and totalStars (to manage the total number of stars displayed).

const [rating, setRating] = useState(null);
const [hover, setHover] = useState(null);
const [totalStars, setTotalStars] = useState(5);
Enter fullscreen mode Exit fullscreen mode

Rendering the Stars

This code snippet dynamically generates the star elements based on the totalStars state. It uses the Array.from() method to create an array of a specified length and then maps over this array to create the star elements. Each star is represented as a radio input and a span element displaying the star symbol (★). The color of the stars changes based on the current rating and hover state.

{[...Array(totalStars)].map((star, index) => {
  const currentRating = index + 1;

  return (
    <label key={index}>
      <input
        type="radio"
        name="rating"
        value={currentRating}
        onChange={() => setRating(currentRating)}
      />
      <span
        className="star"
        style={{
          color:
            currentRating <= (hover || rating) ? "#ffc107" : "#e4e5e9"
        }}
        onMouseEnter={() => setHover(currentRating)}
        onMouseLeave={() => setHover(null)}
      >
        &#9733;
      </span>
    </label>
  );
})}
Enter fullscreen mode Exit fullscreen mode

Total Stars Input

This part of the code provides an input field below the star rating component, allowing users to change the total number of stars displayed. The handleChange function updates the totalStars state based on the value entered by the user in the input field.

<label style={{ fontWeight: 400 }}>
  Number of stars:
  <input
    style={{ marginLeft: "12px", maxWidth: "50px" }}
    onChange={handleChange}
    value={totalStars}
    type="number"
    min={1}
  />
</label>
Enter fullscreen mode Exit fullscreen mode

Styling the Component

.App {
  font-family: sans-serif;
  text-align: center;
}

input[type="radio"] {
  display: none;
}
.star {
  cursor: pointer;
  font-size: 2rem;
  margin: 5px;
}
Enter fullscreen mode Exit fullscreen mode

Here is the reference of the working code


Conclusion:

In summary, the React-based dynamic star rating system demonstrates the fusion of user experience and technological innovation. Through interactive features like hover effects and customizable star counts, this component exemplifies the versatility of modern web development. By empowering users to provide feedback effortlessly, it showcases the importance of user-centric design in creating engaging and responsive web applications.

Feel free to customize and expand upon this foundation to create more complex star rating system functionalities or integrate it into larger applications. If you have any specific questions or need further assistance, don't hesitate to ask! Happy coding! 🚀

Follow Me on Social Media!

If you found this article helpful, feel free to connect with me on LinkedIn and Twitter for more programming tips and tutorials. Let's learn and grow together!

LinkedIn: https://www.linkedin.com/in/kartikbudhraja/

Top comments (0)