How to Build Star Rating Component in React with Material UI

In order to find out how useful or valuable a piece of information is, we use a rating system. The rating system allows users to vote for a series of parameters.

When we think about rating systems, the first thing that strikes us is the generic 5-star rating system.

In this comprehensive guide, we will comprehend how to build a Star Rating system in React Js with the help of React material UI library.

Not just star rating, but we will also teach you how to create a Radio group rating component in React js function component with React MUI.

You will start with building a basic React app, create a functional component, install React MUI, and configure it to build a rating system in React that signifies the user’s interest in the content.

Build New React Project

We only really required a basic React project to get started. You can pretty easily create a new application using the following command.

Please ensure that you enter into the project after it is generated.

npx create-react-app react-blog

Setting Up Material UI in React

There are loads of UI components offered by React MUI. You can only grant access to those modules only after installing the React MUI library.

npm install @mui/material @emotion/react @emotion/styled @fontsource/roboto

Move into the App.css file, then import the fonts package from their respective package.

@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";

Build New Component

Furthermore, you have to create a features folder into the src/ directory along with Home.js file.

Here is the basic function component where you will write code to form the Rating component in React.

import React from 'react'

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

export default Home

Implement Star Rating in React

Ratings deliver acuity regarding others’ opinions and experiences and let the user to submit a rating of their own choice.

We can create controlled, read-only disabled, and no-rating star rating modules.

You have to add and use the code mentioned below in the features/Home.js file.

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 Home() {
  const [value, setValue] = React.useState(2);

  return (
    <Box
      sx={{
        '& > legend': { mt: 2 },
      }}
    >
      <Typography component="legend">Controlled</Typography>
      <Rating
        name="simple-controlled"
        value={value}
        onChange={(event, newValue) => {
          setValue(newValue);
        }}
      />
      <Typography component="legend">Read only</Typography>
      <Rating name="read-only" value={value} readOnly />
      <Typography component="legend">Disabled</Typography>
      <Rating name="disabled" value={value} disabled />
      <Typography component="legend">No rating given</Typography>
      <Rating name="no-value" value={null} />
    </Box>
  );
}

Display Float Number Rating

React MUI rating component comes with greater flexibility. You can show any float number with the value prop.

It would help if you used the precision prop to define the minimum increment value change allowed.

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

export default function Home() {
  return (
    <Stack spacing={1}>
      <Rating name="half-rating" defaultValue={2.5} precision={0.5} />
      <Rating name="half-rating-read" defaultValue={2.5} precision={0.5} readOnly />
    </Stack>
  );
}

Create Hover Feedback

We can show the feedback along with the rating by hovering over the star rating module. We are using the onChangeActive prop’s help in the following 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 Home() {
  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>
  );
}

Star Rating Sizes

We can set the different sizes of the rating using the the size prop.

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

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

Radio Group Rating

In this code example, we are showing ratings and implementing it with a radio group. Make sure to set the highlightSelectedOnly to reform the natural behaviour.

import * as React from 'react';
import PropTypes from 'prop-types';
import { styled } from '@mui/material/styles';
import Rating from '@mui/material/Rating';
import SentimentVeryDissatisfiedIcon from '@mui/icons-material/SentimentVeryDissatisfied';
import SentimentDissatisfiedIcon from '@mui/icons-material/SentimentDissatisfied';
import SentimentSatisfiedIcon from '@mui/icons-material/SentimentSatisfied';
import SentimentSatisfiedAltIcon from '@mui/icons-material/SentimentSatisfiedAltOutlined';
import SentimentVerySatisfiedIcon from '@mui/icons-material/SentimentVerySatisfied';

const StyledRating = styled(Rating)(({ theme }) => ({
  '& .MuiRating-iconEmpty .MuiSvgIcon-root': {
    color: theme.palette.action.disabled,
  },
}));

const customIcons = {
  1: {
    icon: <SentimentVeryDissatisfiedIcon color="error" />,
    label: 'Very Dissatisfied',
  },
  2: {
    icon: <SentimentDissatisfiedIcon color="error" />,
    label: 'Dissatisfied',
  },
  3: {
    icon: <SentimentSatisfiedIcon color="warning" />,
    label: 'Neutral',
  },
  4: {
    icon: <SentimentSatisfiedAltIcon color="success" />,
    label: 'Satisfied',
  },
  5: {
    icon: <SentimentVerySatisfiedIcon color="success" />,
    label: 'Very Satisfied',
  },
};

function IconContainer(props) {
  const { value, ...other } = props;
  return <span {...other}>{customIcons[value].icon}</span>;
}

IconContainer.propTypes = {
  value: PropTypes.number.isRequired,
};

export default function Home() {
  return (
    <StyledRating
      name="highlight-selected-only"
      defaultValue={2}
      IconContainerComponent={IconContainer}
      getLabelText={(value) => customIcons[value].label}
      highlightSelectedOnly
    />
  );
}

Update Main Component

Further, you need to open the App.js file, this file controls the main view of the app.

Hence, you have to import the Home component in this global file.

import React from "react";
import Home from "./features/Home";

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

export default App;

Run React Server

Eventually, we have reached the final step of this guide.

On your console window, type the command you see in the subsequent line and hit enter then.

npm start
http://localhost:3000

How to Build Star Rating Component in React with Material UI