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.
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.
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.
import React, { useState } from "react";
import Rating from "react-rating";
function App() {
const [rating1, setRating1] = useState(0);
return (
<div class="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>
</rating></div>
);
}
export default App;
You will find the more properties to configure a rating component. Check out a few more examples.
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 class="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>
</rating></rating></rating></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.
Output - How to create a rating component in React - Clue Mediator
That’s it for today.
Thank you for reading. Happy Coding..!!