vendredi 19 novembre 2021

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 :

  • when the score is 5, I would like to push star icon 5 times to the "stars" array,
  • when the score is 4, I would like to push star icon 4 times to the "stars" array,
  • when the score is 3, I would like to push star icon 3 times to the "stars" array,
  • when the score is 2, I would like to push star icon 2 times to the "stars" array,
  • when the score is 1, I would like to push star icon 1 time to the "stars" array.

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;

Aucun commentaire:

Enregistrer un commentaire