Create Star Rating Component in React

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to create a star rating component in React. The component will display a set of stars that users can interact with to set the rating value. We will use the useState() hook to manage the state of the component and handle user interactions using onMouseOver, onMouseLeave, and onClick events.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react(("`React`")) -.-> react/AdvancedConceptsGroup(["`Advanced Concepts`"]) react(("`React`")) -.-> react/StateManagementGroup(["`State Management`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") react/FundamentalsGroup -.-> react/conditional_render("`Conditional Rendering`") react/AdvancedConceptsGroup -.-> react/hooks("`React Hooks`") react/StateManagementGroup -.-> react/use_state_reducer("`Using useState and useReducer`") subgraph Lab Skills react/jsx -.-> lab-38362{{"`Create Star Rating Component in React`"}} react/event_handling -.-> lab-38362{{"`Create Star Rating Component in React`"}} react/conditional_render -.-> lab-38362{{"`Create Star Rating Component in React`"}} react/hooks -.-> lab-38362{{"`Create Star Rating Component in React`"}} react/use_state_reducer -.-> lab-38362{{"`Create Star Rating Component in React`"}} end

Star Rating

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

Create a Star component that renders each individual star with the appropriate appearance based on the parent component's state. Then, define a StarRating component that uses the useState() hook to define the rating and selection state variables with the appropriate initial values.

In StarRating, create a method named hoverOver that updates selection according to the provided event. If event is not provided or it is null, reset selection to 0. Use the .data-star-id attribute of the event's target to determine the value of selection.

Next, create an array of 5 elements using Array.from() and create individual <Star> components using Array.prototype.map(). Handle the onMouseOver and onMouseLeave events of the wrapping element using hoverOver. Handle the onClick event using setRating.

.star {
  color: #ff9933;
  cursor: pointer;
}
const Star = ({ marked, starId }) => {
  return (
    <span data-star-id={starId} className="star" role="button">
      {marked ? "\u2605" : "\u2606"}
    </span>
  );
};

const StarRating = ({ value }) => {
  const [rating, setRating] = React.useState(parseInt(value) || 0);
  const [selection, setSelection] = React.useState(0);

  const hoverOver = (event) => {
    let val = 0;
    if (event && event.target && event.target.getAttribute("data-star-id"))
      val = event.target.getAttribute("data-star-id");
    setSelection(val);
  };

  return (
    <div
      onMouseLeave={() => hoverOver(null)}
      onMouseOver={hoverOver}
      onClick={(e) =>
        setRating(e.target.getAttribute("data-star-id") || rating)
      }
    >
      {Array.from({ length: 5 }, (v, i) => (
        <Star
          starId={i + 1}
          key={`star_${i + 1}`}
          marked={selection ? selection >= i + 1 : rating >= i + 1}
        />
      ))}
    </div>
  );
};

Finally, render the StarRating component with an initial value of 2 by calling ReactDOM.createRoot(document.getElementById('root')).render(<StarRating value={2} />);.

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Star Rating lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like