Ant Design Library has this component pre-built, and it is very easy to integrate as well. Rate Component helps in capturing the user feedback in form of rating. We can use the following approach in ReactJS to use the Ant Design Rate Component.
Rate Methods:
- blur(): This method is used to remove the focus from the element.
- focus(): This method is used to get the focus on the element.
Rate Props:
- allowClear: It is used to specify whether to allow clear the rating when the user clicks again on it.
- allowHalf: It is used to indicate whether to allow semi selection of rating or not.
- autoFocus: It is used to get the focus when the component is mounted.
- character: It is used to denote the custom character of rate.
- className: It is used to specify the class name for the rate.
- count: It is used to denote the start count.
- defaultValue: It is used to define the default value for the rate.
- disabled: It is used to disable the component.
- style: It is used to specify the custom style object for the rate.
- tooltips: It is used to customize the tooltip by each character.
- value: It is used to denote the current value.
- onBlur: It is a callback function that is triggered when the component loses focus.
- onChange: It is a callback function that is triggered when a value is selected.
- onFocus: It is a callback function that is triggered when the component gets focus.
- onHoverChange: It is a callback function that is triggered when an item is hover.
- onKeyDown: It is a callback function that is triggered when keydown on component
Creating React Application And Installing Module:
-
Step 1: Create a React application using the following command:
npx create-react-app foldername
-
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
-
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install antd
Project Structure: It will look like the following.
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React, { useState } from 'react' import "antd/dist/antd.css" ; import { Rate } from 'antd' ; export default function App() { const [currentValue, setCurrentValue] = useState(2) return ( <div style={{ display: 'block' , width: 700, padding: 30 }}> <h4>ReactJS Ant-Design Rate Component</h4> <Rate onChange={(value) => { setCurrentValue(value) }} value={currentValue} /> <br /> Current Rating: {currentValue} </div> ); } |
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:
Reference: https://ant.design/components/rate/