How can I make this "if" statement more clean and efficient?


I’m trying to optimize/clean the "if" statement. As you can see the code, it looks… pretty long and inefficient. If you were me, how would you fix and make it look/work better?

To explain about what I’m trying to build :

Code

import React, { useState } from "react";
import { AiFillStar } from "react-icons/ai";

const Review = ({ title, comment, score }) => {

  let stars = [];

  if (score == 5) {
    stars.push(<AiFillStar />);
    stars.push(<AiFillStar />);
    stars.push(<AiFillStar />);
    stars.push(<AiFillStar />);
    stars.push(<AiFillStar />);
  }

  if (score == 4) {
    stars.push(<AiFillStar />);
    stars.push(<AiFillStar />);
    stars.push(<AiFillStar />);
    stars.push(<AiFillStar />);
  }

  if (score == 3) {
    stars.push(<AiFillStar />);
    stars.push(<AiFillStar />);
    stars.push(<AiFillStar />);
  }

  if (score == 2) {
    stars.push(<AiFillStar />);
    stars.push(<AiFillStar />);
  }

  if (score == 1) {
    stars.push(<AiFillStar />);
  }

 
  return (
    <div className="review-container">
      <p>Title: {title}</p>
      <p>Comment: {comment}</p>
      {/* <p>Score: {star}</p> */}
      {stars.map((star) => star)}
    </div>
  );
};

export default Review;

Source: React – Stack Overflow

November 19, 2021
Category : News
Tags: if-statement | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.