How to create a rating component in ReactJS ?
The following approach covers how to create a rating component in React JS.
- Basic knowledge of npm & create-react-app command.
- Basic Knowledge of styled-components.
- Basic Knowledge of useState() React hooks.
Basic Setup: You will start a new project using create-react-app command:
npx create-react-app react-rating
Now go to your react-rating folder by typing the given command in the terminal.
Required module: 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.
We create a state with the first element rate as an initial state having a value of 0 and the second element as function setRate() for updating the state. Index numbers ranging from 0 to 4 are assigned with an addition of 1 to the newly initialized variable givenRating . While mapping the array using Map() method, we associate the value of givenRating variable with each of the five radio buttons (for example, 1 for the first button and so on).
We update the value of the state with the help of onClick function which sets its value equal to givenRating whenever it is called. For example, if we click on the 4th star (from left), we know the value of givenRating associated with this star (or radio button) is 4. This value of 4 gets assigned to our state. Now the role of the conditional operator comes into play. Only those radio buttons get selected (or change their color) which have a value equal to or less than 4. So as a result, we get a four-star rating.
Step to Run Application: Run the application using the following command from the root directory of the project:
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: