Home > Software design >  Replace a Number Value with Icons
Replace a Number Value with Icons

Time:11-03

So in a React project I have a line:

<div className="star-rating fas fa-star">{data?.starRating}</div>

This returns a Number between 1-5, but how do I replace that Number with a number of Star Icons? For example, a 3 Returns 3 Stars, 4 Returns 4 Stars etc.

Currently the CSS for this:

.star-rating{
  float: right;
  width: 50%;
  margin-bottom: 1em;
  font-family: FontAwesome;
  content: "\f005";
  font-size: 1.5em;
  color: #FFD700;
}

But all this does is make the Number Yellow and not replace it with any icon

CodePudding user response:

You can use repeat:

function App({ stars }) {
  return <p className="stars">{"★".repeat(stars)   "☆".repeat(5 - stars)}</p>
}

ReactDOM.render(<App stars={4} />, document.getElementById("root"));
.stars { color: yellow }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

CodePudding user response:

Using react methods you can make it like this

<div className="star-rating fas fa-star">
  {data?.starRating.map(_ => (
    <YourStarComponent />
  ))}
</div>
  • Related