project image

Create star rating component with React and Typescript 

Overview

Rating systems are a common feature in many applications, from e-commerce websites to movie review platforms. Implementing a star rating component is a great way to enhance user interaction and feedback. In this tutorial, we will walk through the process of creating a star rating component using React and Typescript. By the end, you'll have a reusable and customizable star rating component that you can integrate into your projects.

User feedback is a crucial part of any online platform, and star ratings are a simple and effective way to collect it. In this blog post, we'll guide you through the process of creating a star rating component using React and TypeScript. By the end of this tutorial, you'll have a reusable and customizable star rating component that you can integrate into your web applications.

 

Setting Up the Project

 

Let's start by setting up a new React project with Typescript. Open your terminal and run the following commands:


npx create-react-app star-rating-demo --template typescript
cd star-rating-demo

This will create a new React project with Typescript support.

 

Create the Star-Rating Component

 

In your project directory, navigate to the src folder and create a new file called Star.tsx. This file will contain our star rating component.

Here, we are describing two approaches to creating this component.

 

Styled with CSS

 

// Star.tsx

import React from "react";

export const Star = ({ rating, maxRating, onRate }) => {
  return (
    <div className="star_container">
      {Array(maxRating)
        .fill(null)
        .map((el, i) => (
          <div
            className="star"
            onClick={() => {
              onRate?.(i + 1);
            }}
            style={{
              fill: rating > i ? "var(--color)" : undefined,
            }}
          >
            <svg height="25" width="23" data-rating="1">
              <polygon points="9.9, 1.1, 3.3, 21.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78" />
            </svg>
          </div>
        ))}
    </div>
  );
};

 

Styled with JS

 

// Star.tsx

import React from "react";

export const StarWithJS = ({ rating, maxRating, onRate }) => {
  const [hoverVal, setHoverVal] = React.useState(0);
  return (
    <div style={{ display: "flex" }}>
      {Array(maxRating)
        .fill(null)
        .map((el, i) => (
          <div
            onClick={() => {
              onRate?.(i + 1);
            }}
            style={{
              fill: rating > i || hoverVal > i ? "orange" : undefined
            }}
            onMouseEnter={() => {
              setHoverVal(i + 1);
            }}
            onMouseLeave={() => {
              setHoverVal(0);
            }}
          >
            <svg height="25" width="23" data-rating="1">
              <polygon points="9.9, 1.1, 3.3, 21.78, 19.8, 8.58, 0, 8.58, 16.5, 21.78" />
            </svg>
          </div>
        ))}
    </div>
  );
};

In this component, we're accepting three props

  • rating — Current rating input
  • maxRating — maximum rating range
  • onRate — an event which will fire when we click on stars

 

Styling the Star Rating

 

let's create some basic styles for our star rating component. Create a new file called styles.css in the same directory as your component file and add the following styles:

/* styles.css */

* {
  --color: orange;
}
.App {
  font-family: sans-serif;
  text-align: center;
}
.star_container {
  display: flex;
}
.star_container:hover .star {
  fill: var(--color);
}
.star_container:hover .star:hover ~ .star {
  fill: initial;
}

 

Implementing the Star Rating Component

 

Now that our star rating component and its styles are ready, let's integrate it into a sample application. Open the src/App.tsx file and replace its content with the following code:

// src/App.tsx

import React from "react";
import { Star, StarWithJS } from "./Star";
import "./styles.css";

export default function App() {
  const [rating, setRating] = React.useState(0);
  return (
    <div className="App" style={{ display: "flex", flexDirection: "column" }}>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-evenly"
        }}
      >
        <p>With CSS</p>
        <Star maxRating={5} rating={rating} onRate={setRating} />
      </div>
      <div
        style={{
          display: "flex",
          alignItems: "center",
          justifyContent: "space-evenly"
        }}
      >
        <p>With JS</p>
        <StarWithJS maxRating={5} rating={rating} onRate={setRating} />
      </div>
    </div>
  );
}

In this code, we're importing the Star component and using it inside the App component.

 

Running the Application

 

To see the star rating component in action, run the following command in your project directory:

npm start

This will start the development server, and you can view the star rating component by opening your browser and visiting http://localhost:3000.

star-rating.gif

 

You can customize the star rating component further by adding features like read-only mode, half-star ratings, or custom styling. Experiment with the component to suit your specific requirements. 

Congratulations! You've successfully created a star rating component using React and Typescript. Feel free to explore more advanced features and incorporate this component into your projects for user-friendly rating interactions.

 

 

Conclusion

 

Creating a 5-star rating component with React and TypeScript is a useful addition to your web development toolbox. You can easily customize and reuse this component in various parts of your application. By following the steps outlined in this blog post, you'll be able to create a flexible and interactive star rating component that enhances the user experience of your web applications. Happy coding!