How to add rating stars in react js?
August 23, 2024Hi Friends π,
Welcome To aHoisting!
To add rating stars in react js, you can use setRating(currentRating)
. It will add rating stars in react js.
Today, I am going to show you, how to add rating stars in react js.
Table of contents
- Install and create a new React app.
- Import react component.
- Create a Component.
Letβs start with the first step.
Step 1: Install and create a new React app.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import react component.
After installing, you have to import your React component.
import React, { useState } from "react";
import "./App.css";
Step 3: Create a Component.
You can use value={totalStars}
to add rating stars in react js.
<label style={{ fontWeight: 400 }}>
Number of stars:
<input
style={{ marginLeft: "12px", maxWidth: "50px" }}
onChange={handleChange}
value={totalStars}
type="number"
min={1}
/>
</label>
Add rating stars example.
The below code is an example of a React. You have to import "./App.css"
and set setRating(currentRating)
to add rating stars in react js.
App.js
import React, { useState } from "react";
import "./App.css";
export default function App() {
const [rating, setRating] = useState(null);
const [hover, setHover] = useState(null);
const [totalStars, setTotalStars] = useState(5);
const handleChange = (e) => {
setTotalStars(parseInt(Boolean(e.target.value, 10) ? e.target.value : 5));
};
return (
<div className="App">
<h1>Star rating</h1>
{[...Array(totalStars)].map((star, index) => {
const currentRating = index + 1;
return (
<label key={index}>
<input
key={star}
type="radio"
name="rating"
value={currentRating}
onChange={() => setRating(currentRating)}
/>
<span
className="star"
style={{
color:
currentRating <= (hover || rating) ? "#ffc107" : "#e4e5e9",
}}
onMouseEnter={() => setHover(currentRating)}
onMouseLeave={() => setHover(null)}
>
★
</span>
</label>
);
})}
<br />
<br />
<p>Your rating is: {rating}</p>
<br />
<label style={{ fontWeight: 400 }}>
Number of stars:
<input
style={{ marginLeft: "12px", maxWidth: "50px" }}
onChange={handleChange}
value={totalStars}
type="number"
min={1}
/>
</label>
</div>
);
}
App.css
.App {
font-family: sans-serif;
text-align: center;
}
input[type="radio"] {
display: none;
}
.star {
cursor: pointer;
font-size: 2rem;
margin: 5px;
}
In the above code example, I have used the setRating(currentRating)
to add rating stars in react js.
Check the output of the above code.
All the best π