How to create a rating component in React
Today we’ll show you how to create a rating component in React. In this short article, we will use the npm package to build rating component in the ReactJS.
Let’s check an example where we will simply implement the rating component and on selection, we’ll display the selected value.
Steps to create a rating component
1. Create react application
First of all, we will set up the startup react application using the create-react-app
package. Run the following command to create a react app.
1 | npx create-react-app rating-react-component |
2. Add npm dependency
To integrate a rating component, we have to install the react-rating npm package. Run the following command to add dependency.
1 | npm i react-rating |
3. Add rating component
Let’s integrate the rating component in the react application. Basic integration is very straight forward using the react-rating
package.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import React, { useState } from "react"; import Rating from "react-rating"; function App() { const [rating1, setRating1] = useState(0); return ( <div className="App"> <h3>Rating Component - <a href="https://cluemediator.com/" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3> <strong>Example 1</strong> <Rating initialRating={rating1} onClick={rate => setRating1(rate)} /> <p>Rating: {rating1}</p> </div> ); } export default App; |
You will find the more properties to configure a rating component. Check out a few more examples.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import React, { useState } from "react"; import Rating from "react-rating"; function App() { const [rating1, setRating1] = useState(0); const [rating2, setRating2] = useState(0); const [rating3, setRating3] = useState(0); return ( <div className="App"> <h3>Rating Component - <a href="https://cluemediator.com/" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3> <strong>Example 1</strong> <Rating initialRating={rating1} onClick={rate => setRating1(rate)} /> <p>Rating: {rating1}</p> <strong>Example 2</strong> <Rating fractions={2} stop={10} initialRating={rating2} onClick={rate => setRating2(rate)} /> <p>Rating: {rating2}</p> <strong>Example 3</strong> <Rating fractions={2} emptySymbol="fa fa-star-o fa-2x star" fullSymbol="fa fa-star fa-2x star" initialRating={rating3} onClick={rate => setRating3(rate)} /> <p>Rating: {rating3}</p> </div> ); } export default App; |
In the above example 3, we have used the Font Awesome class to change the rating symbol.
4. Output
Run the application and check the output in the browser.
That’s it for today.
Thank you for reading. Happy Coding..!!