Home > Software design >  How to create a rating component with stars (filled or unfilled) on React js?
How to create a rating component with stars (filled or unfilled) on React js?

Time:11-26

I want to know how to create a rating component with filled or unfilled stars based on the information in my json files. I already have the rating number on my json file, I must put it on my rating component.

import React, { useRef, useState } from "react";
import { ReactComponent as Star } from "../assets/star.png";
import logements from "../data/logements.json";
import "../style/Stars.css";

function Stars(rating, color) {
  const rating = useRef();
  const [starfilled, setStarFilled] = useState(0);
  const [starUnfilled, setStarUnfilled] = useState(0);

  function ratingStars() {
    if (rating.length >= 0) {
      setStarFilled(starfilled  );
    } else {
      setStarUnfilled(starUnfilled(0));
    }
  }

  return (
    <div>
      <img src={Star} className="starStyle" alt='star'></img>
    </div>
  );
}

export default Stars;

CodePudding user response:

You could set a CSS custom property on the containing element indicating the rating as a percentage, and then use that to fill the appropriate number of stars.

.demo {
  display: inline-flex;
  flex-direction: column;
}

.stars {
  position: relative;
  display: inline-block;
}

.bg {
  opacity: 0.35;
  filter: grayscale(1);
}

.stars::after {
  content: '⭐⭐⭐⭐⭐';
  position: absolute;
  top: 0;
  left: 0;
  width: calc(100% * var(--rating));
  overflow: hidden;
}
<div >
  <div  style="--rating: 0.1">
    <div >⭐⭐⭐⭐⭐</div>
  </div>

  <div  style="--rating: 0.2">
    <div >⭐⭐⭐⭐⭐</div>
  </div>

  <div  style="--rating: 0.4">
    <div >⭐⭐⭐⭐⭐</div>
  </div>

  <div  style="--rating: 0.5">
    <div >⭐⭐⭐⭐⭐</div>
  </div>

  <div  style="--rating: 0.6">
    <div >⭐⭐⭐⭐⭐</div>
  </div>

  <div  style="--rating: 0.8">
    <div >⭐⭐⭐⭐⭐</div>
  </div>

  <div  style="--rating: 1">
    <div >⭐⭐⭐⭐⭐</div>
  </div>
</div>

CodePudding user response:

Found some example on net. Basically displaying star icon based on previous set data (for display only, use disabled=true prop, check the commented implementation of component).

https://codepen.io/benjaminreid/pen/vNVwPW

And here step by step guideline with same concept https://dev.to/michaelburrows/create-a-custom-react-star-rating-component-5o6

Edit: @Ray answer also quite simpler. You can accustom style display for decimal rating. By having 5 star as --rating=1 (5/5=1 or rating/5)

  • Related