How to Make Star Rating in React (2024)

For my capstone project at Flatiron School, I created an application in which users can track and manage the eateries (ex: restaurants, cafes/bakeries/coffee shops, & bars/breweries) they have visited and the food and drink they ordered so visits can be referenced at a later time.

One of the features I wanted to include was a rating functionality. Instead of displaying just numerical ratings, I wanted to display those ratings via star icons. In addition to displaying those numerical ratings into stars, I wanted users to be able to click on the stars to create or edit their rating for an eatery.

I used a React frontend to accomplish this task. I will first describe how to display ratings via stars, and then describe how to dynamically change the star ratings when creating or editing a rating.

How to Convert Numerical Rating into Star Rating

Inside the component that holds and displays the eatery rating, I first declared a constant that holds the colors of the stars when they are empty and filled (this can alternatively be done via inline styling).

const colors = { orange: "#F2C265", grey: "a9a9a9" }

One of my attributes of an Eatery is the "rating" declared as an integer on the backend. This numerical, integer rating was then translated into stars in React. To create the stars, I first installed the React Icons Kit library and selected the FaStar icon, and imported it into my component. I then created an array of 5 stars, called "stars", where the .fill was 0.

Now, in my return, this is where the star rating is displayed on the page. I mapped over the star array and returned the star icon where the color of the star is filled based on the rating of the specific eatery. For example, if a user gave the eatery 4 stars, 4/5 stars would be filled in with the color = orange, and 1/5 stars would remain the color = grey. (I also chose to display the numerical star rating next to the star icons.)

return ( <div> {stars.map((_, index) => { return ( <FaStar key={index} size={24} color={(rating) > index ? colors.orange : colors.grey} /> <p>({rating} Stars)</p> ) })} </div>);

How to Make Star Rating in React (1)

How to Dynamically Create and Edit Star Icon Rating

Display a static rating via star icons is more simplistic than creating dynamically changing star icons. Dynamically creating or editing star icon ratings requires useState and event listeners. The same React icon was imported and the same color constant and star array described above were also created.

First, inside the component where I want to create (or edit) a star icon rating, I created two states. One for the rating attribute, with the initial state set as the current rating (if the user was editing the rating). The other state was created for selecting the stars when rating called "hoverValue". Initial state for the rating attribute was set as the current rating (if the user was editing the rating). Initial state was declared as undefined because we don't want to give the hoverValue a pre-determined state - we want it to be 0 before we start rating.

const [rating, setRating] = useState(eatery.rating)const [hoverValue, setHoverValue] = useState(undefined)

When rating, I wanted to hover over the stars and have them be filled with the orange color before settling on the final rating. To do this, I added a some event listeners to handle this functionality:

const handleMouseOverStar = value => { setHoverValue(value)};const handleMouseLeaveStar = () => { setHoverValue(undefined)}

The handleMouseOver takes in a value when the user hovers over the star icons and sets that value in the setHoverValue setter function. The handleMouseLeaveStar removes the stars when an user moves away from the stars (i.e. wants to reduce the amount of stars they have chosen).

const handleClickStar = value => { setRating(value)};

The handleClickStar takes the value of the rating a user choses via a mouse click and sets that value to the setRating setter function. This means, the number of stars a user selects will be the rating of the eatery.

Now, we need to actually display this functionality on the page. In the return, we are going to map over the stars array (like before) and now include the event listeners.

return ( <div> {stars.map((_, index) => { return ( <FaStar key={index} size={24} value={rating} onChange={(e) => setRating(e.target.value)} color={(hoverValue || rating) > index ? colors.orange : colors.grey} onClick={() => handleClickStar(index + 1)} onMouseOver={() => handleMouseOverStar(index + 1)} onMouseLeave={() => handleMouseLeaveStar} /> ) })} </div>);

The onChange event listener manages the setting of the rating, the onClick event listener manages the incrementation of the star icon rating, and the onMouseOver and onMouseLeave manage the hover effects of the star rating.

It is difficult to show the functionality of this hover star rating via images, but if you are curious how this works, you can play around with it on my website:

I think this functionality is a fun feature to add to any website that includes rating, and I hope this tutorial was helpful!

How to Make Star Rating in React (2024)
Top Articles
Yes, Banks Have Collapsed. But Your Money Is Likely Safe
Uses of Electricity: Learn Applications In Daily Life, Importance
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Rev. Porsche Oberbrunner

Last Updated:

Views: 5618

Rating: 4.2 / 5 (73 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Rev. Porsche Oberbrunner

Birthday: 1994-06-25

Address: Suite 153 582 Lubowitz Walks, Port Alfredoborough, IN 72879-2838

Phone: +128413562823324

Job: IT Strategist

Hobby: Video gaming, Basketball, Web surfing, Book restoration, Jogging, Shooting, Fishing

Introduction: My name is Rev. Porsche Oberbrunner, I am a zany, graceful, talented, witty, determined, shiny, enchanting person who loves writing and wants to share my knowledge and understanding with you.