How to Calculate the Average of Ratings in React
In today's lesson, we will see how to calculate the average of ratings in react js, let's assume that we have a list of products that have many ratings and we want to calculate and show the average of ratings.
Install the package
First, let's install the package we need.
npm i react-simple-star-rating
Calculate the average of ratings
Next, we will calculate and show the average of ratings.
import React from 'react';
import { Rating } from 'react-simple-star-rating';
export default function ProductRatings() {
const reviews = [
{
product: 1,
rating: 4
},
{
product: 2,
rating: 5
},
{
product: 3,
rating: 3
},
{
product: 4,
rating: 2
},
{
product: 5,
rating: 5
}
]
const calculateReviewsAverage = () => {
let average = reviews.reduce((acc,review) => {
return acc + review.rating / reviews.length;
},0);
return average > 0 ? average.toFixed(1) : 0;
}
return (
<Rating initialValue={calculateReviewsAverage()}
readonly
size={24} />
)
}