How to create a rating component in ReactJS ?
Last Updated :
04 Dec, 2023
React JS is a powerful JavaScript library for building user interfaces, and it provides a flexible and efficient way to create reusable components. One common component in many web applications is a rating system, which allows users to provide feedback or rate certain items. In this article, we will explore how to create a rating component in ReactJS.
Prerequisite:
Steps to create React App and Install required modules
Step 1: You will start a new project using create-react-app command
npx create-react-app react-rating
Step 2: Now go to your react-rating folder by typing the given command in the terminal.
cd react-rating
Step 3: Install the dependencies required in this project by typing the given command in the terminal.
npm install --save styled-components
npm install --save react-icons
Now create the components folder in src then go to the components folder and create two files Rating.js and RatingStyles.js.
Project Structure: The file structure in the project will look like this.
Example: In this example, we will design a rating component, for that we will need to manipulate the App.js file and other created components file.
Rating.js
import React, { useState } from "react" ;
import { FaStar } from "react-icons/fa" ;
import { Container, Radio, Rating } from "./RatingStyles" ;
const Rate = () => {
const [rate, setRate] = useState(0);
return (
<Container>
{[...Array(5)].map((item, index) => {
const givenRating = index + 1;
return (
<label>
<Radio
type= "radio"
value={givenRating}
onClick={() => {
setRate(givenRating);
alert(
`Are you sure you want to give
${givenRating} stars ?`
);
}}
/>
<Rating>
<FaStar
color={
givenRating < rate || givenRating === rate
? "000"
: "rgb(192,192,192)"
}
/>
</Rating>
</label>
);
})}
</Container>
);
};
export default Rate;
|
RatingStyles.js
import styled from 'styled-components' ;
export const Container = styled.div`
display: flex;
justify-content: center;
align-items: center;
min-height: 60vh;
font-size: 60px;
`
export const Radio = styled.input`
display: none;
`
export const Rating = styled.div`
cursor: pointer;
`
|
App.js
import './App.css' ;
import Rating from './components/Rating' ;
function App() {
return (
<Rating />
);
}
export default App;
|
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...