React Readonly fractional rating

React Readonly Fractional Rating

As someone who has built multiple rating systems for web applications, I understand the importance of allowing users to rate items using fractional values. With React, it is possible to build a readonly fractional rating system that allows users to view ratings in decimal format.

Using React State

To build a readonly fractional rating system, it is important to use React state to store the rating value. This value can be set using a default value or by fetching it from an API. Once the rating value is set, it can be displayed in decimal format using the following code:


import React, { useState } from 'react';

const ReadOnlyRating = ({ rating }) => {
  const [value, setValue] = useState(rating);

  return (
    <div>
      {value.toFixed(1)}
    </div>
  );
}

Using Props

Another way to build a readonly fractional rating system is by passing the rating value as a prop to the component. This method is useful when the rating value is fetched from an API or passed down from a parent component.


import React from 'react';

const ReadOnlyRating = ({ rating }) => (
  <div>
    {rating.toFixed(1)}
  </div>
);

Using CSS

To style the readonly fractional rating system, CSS can be used to add stars or other icons to represent the rating value. This can be done using CSS pseudo-elements and setting the width of the element based on the rating value.


.rating {
  position: relative;
  display: inline-block;
  font-size: 0;
}

.rating:before {
  content: "★";
  position: absolute;
  left: 0;
  color: gold;
}

.rating:after {
  content: "☆";
  position: absolute;
  left: 0;
  color: grey;
}

.rating .stars:before {
  content: "★";
  font-size: 24px;
  line-height: 1;
  color: gold;
}

.rating .stars:after {
  content: "☆";
  font-size: 24px;
  line-height: 1;
  color: grey;
}

.rating .stars:before {
  width: ${({ rating }) => rating}%;
  z-index: 2;
}

.rating .stars:after {
  z-index: 1;
}

The above CSS code will display a star rating system with gold stars representing the rating value and grey stars representing the remaining rating value. The width of the gold stars is set based on the rating value passed to the component.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe