React 18 Material UI Star Rating Component Example Tutorial

Last Updated on by in React JS

The star rating system is an extraordinarily facile and easy-to-use component. Mainly used to give feedback, it allows us to evaluate a statement on a visual scale of stars.

In this tutorial, you will learn how to create a Star Rating component in React using React material UI module with a functional component.

Not only but also, we will show you how to customize the star rating in React using React Material UI pre-defined properties.

We will demonstrate in simple steps how to change the stars’ size and the star rating icons in React.

How to change the star rating events among click and hover. Also, how to set the disable state of the React star rating component.

Ideally, a 5-star rating system authorises respondents to rank their feedback on a 5-point scale from 1 to 5. The more the stars are chosen, the better the response is received.

Let’s see the best way to implement star rating in React JS with React MUI.

How to Create Click and Hover Star Rating System in React JS using Material UI

  • Step 1: Create New Project
  • Step 2: Install React Material UI
  • Step 3: Make Function Component
  • Step 4: Build Simple Star Rating Component
  • Step 5: Read Only Star Rating
  • Step 6: Disable Star Rating
  • Step 7: Hover Star Rating Feedback
  • Step 8: Customize Star Rating
  • Step 9: Update Main Component
  • Step 10: Test App on Browser

Create New Project

You must have node, npm set up in your computer. Make sure to create the new application from using the following command.

npx create-react-app react-blog-app

Navigate to the project directory.

cd react-blog-app

Install React Material UI

In this section, we will guide you through adding the cardinal elements of this tutorial.

Go ahead and run the command to install React Material UI and specific other packages.

npm i @mui/material @emotion/react @emotion/styled --legacy-peer-deps
npm install @fontsource/roboto --legacy-peer-deps

Now the modules are added, you now have to import CSS associated to React MUI in the App.css file.

@import url("https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap");
@import "@fontsource/roboto/300.css";
@import "@fontsource/roboto/400.css";
@import "@fontsource/roboto/500.css";
@import "@fontsource/roboto/700.css";

Make Function Component

In this section, you have to create components/ directory along with the StarRating.js file.

import React from 'react'

function StarRating() {
  return (
    <div>StarRating</div>
  )
}

export default StarRating

Build Simple Star Rating Component

To create the Star Rating component you require to insert the whole code, even line by line in the components/StarRating.js file.

import * as React from "react";
import Box from "@mui/material/Box";
import Rating from "@mui/material/Rating";

export default function StarRating() {
  const [value, setValue] = React.useState(2);

  return (
    <Box
      sx={{
        "& > legend": { mt: 2 },
      }}
    >
      <Rating
        name="simple-controlled"
        value={value}
        onChange={(event, newValue) => {
          setValue(newValue);
        }}
      />
    </Box>
  );
}

Read Only Star Rating

A read only star feedback review system in React JS can be created by just passing the name="read-only" and readOnly properties

import * as React from "react";
import Box from "@mui/material/Box";
import Rating from "@mui/material/Rating";
import Typography from "@mui/material/Typography";

export default function StarRating() {
  const [value, setValue] = React.useState(2);

  return (
    <Box
      sx={{
        "& > legend": { mt: 2 },
      }}
    >
      <Typography component="legend">Read only</Typography>
      <Rating name="read-only" value={value} readOnly />
    </Box>
  );
}

Disable Star Rating

In this phase, we will take a closer look at how to disable the star review component in React.

It is pretty straightforward. We only need to set name=”disabled” and disabled props.

import * as React from "react";
import Box from "@mui/material/Box";
import Rating from "@mui/material/Rating";
import Typography from "@mui/material/Typography";

export default function StarRating() {
  const [value, setValue] = React.useState(2);

  return (
    <Box
      sx={{
        "& > legend": { mt: 2 },
      }}
    >
      <Typography component="legend">Disabled</Typography>
      <Rating name="disabled" value={value} disabled />
    </Box>
  );
}

Hover Star Rating Feedback

We will now show a label on hover to allow the user to choose the correct rating value.

We will use the onChange and onChangeActive event handler props in the code example.

import * as React from "react";
import Rating from "@mui/material/Rating";
import Box from "@mui/material/Box";
import StarIcon from "@mui/icons-material/Star";

const labels = {
  0.5: "Useless",
  1: "Useless+",
  1.5: "Poor",
  2: "Poor+",
  2.5: "Ok",
  3: "Ok+",
  3.5: "Good",
  4: "Good+",
  4.5: "Excellent",
  5: "Excellent+",
};

function getLabelText(value) {
  return `${value} Star${value !== 1 ? "s" : ""}, ${labels[value]}`;
}

export default function StarRating() {
  const [value, setValue] = React.useState(2);
  const [hover, setHover] = React.useState(-1);

  return (
    <Box
      sx={{
        width: 200,
        display: "flex",
        alignItems: "center",
      }}
    >
      <Rating
        name="hover-feedback"
        value={value}
        precision={0.5}
        getLabelText={getLabelText}
        onChange={(event, newValue) => {
          setValue(newValue);
        }}
        onChangeActive={(event, newHover) => {
          setHover(newHover);
        }}
        emptyIcon={<StarIcon style={{ opacity: 0.55 }} fontSize="inherit" />}
      />
      {value !== null && (
        <Box sx={{ ml: 2 }}>{labels[hover !== -1 ? hover : value]}</Box>
      )}
    </Box>
  );
}

Customize Star Rating

Based on our requirements and preferred scenario, we can change the star rating size using size prop.

import * as React from 'react';
import Rating from '@mui/material/Rating';
import Stack from '@mui/material/Stack';

export default function StarRating() {
  return (
    <Stack spacing={1}>
      <Rating name="size-small" defaultValue={3} size="small" />
      <Rating name="size-medium" defaultValue={2} />
      <Rating name="size-large" defaultValue={3} size="large" />
    </Stack>
  );
}

When it comes to customization of star feedback ratings, react MUI gives us the utmost flexibility.

We can change the star icon to any icon and even increase or decrease the number of stars.

import * as React from "react";
import { styled } from "@mui/material/styles";
import Box from "@mui/material/Box";
import Rating from "@mui/material/Rating";
import FavoriteIcon from "@mui/icons-material/Favorite";
import FavoriteBorderIcon from "@mui/icons-material/FavoriteBorder";
import Typography from "@mui/material/Typography";

const StyledRating = styled(Rating)({
  "& .MuiRating-iconFilled": {
    color: "#ff6d75",
  },
  "& .MuiRating-iconHover": {
    color: "#ff3d47",
  },
});

export default function StarRating() {
  return (
    <Box
      sx={{
        "& > legend": { mt: 2 },
      }}
    >
      <Typography component="legend">Custom icon and color</Typography>
      <StyledRating
        name="customized-color"
        defaultValue={2}
        getLabelText={(value) => `${value} Heart${value !== 1 ? "s" : ""}`}
        precision={0.5}
        icon={<FavoriteIcon fontSize="inherit" />}
        emptyIcon={<FavoriteBorderIcon fontSize="inherit" />}
      />
      <Typography component="legend">10 stars</Typography>
      <Rating name="customized-10" defaultValue={2} max={10} />
    </Box>
  );
}

Update Main Component

Earlier we formed the star component — however, it won’t work alone.

This component needs to be injected in the app; you can do it by importing it inside the main App.js file.

import React from "react";
import StarRating from "./components/StarRating";

function App() {
  return (
    <div>
      <h2>React Material UI Star Rating Example</h2>
      <StarRating />
    </div>
  );
}

export default App;

Test App on Browser

Well, this extensive guide aims to show you how things work in a real-world scenario. Therefore, we will start the app server using the suggested command.

npm start

If you are building the feature locally then you may use this url to run the app.

http://localhost:3000

React Material UI Star Rating Component Example Tutorial

Conclusion

This tutorial taught us how to build a simple star rating survey component using React MUI.

Not only but also, we ascertained how to customize the star rating review system using custom material UI properties.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.