Possible to multiply or concat JSX?

I'm using React along with Font Awesome to create a row of stars. I have a function that takes a number and produces that many stars. I'm trying to find the best way to do this within a react component. Basically, I need to multiply the JSX element by a number to get it to repeat dynamically based on what's passed in:

reviewStars(num) {
    const star = <i className="fa fa-star" aria-hidden="true"></i>;
    const getStarCount = star.repeat(num);
    return getStarCount;
  };

If the JSX was a string, this would work, but because it's not, I can't call repeat on it (error says star is not a function). I could wrap it in single quotes '' and then replace those, but wondering if there is a better handle to this? Thanks.

Answers:

Answer

Try something like this:

reviewStars(num) {
  let stars = [];
  for(let i= 0; i < num; i++) {
    stars.push(<i key={i} className="fa fa-star" aria-hidden="true"></i>);
  }
  return (
    <div>{stars}</div>
  );
};

edit: remember to add key to lists

Answer

In order to maintain validity of JSX, you would first need to wrap sibling elements in a parent element, either a <span> or a <div>.

Afterwards you would have to loop num times and repeat your JSX for the star, accumulating it in a variable that you will return inside that wrapper.

Something like this should do the trick for you

reviewStars(num) {
   let stars = [];

   for (let i = 0; i < num; i++) {
       stars.push(<i className="fa fa-star" aria-hidden="true" key={i} />;
   }

   return (
       <span>
          {stars}
       </span>
   );
};
Answer

Array.from() method creates an array with specified length. See MDN here.

<div>
{ Array.from({ length: num }, (_, i) =>
    <i key={i} className="fa fa-star" aria-hidden="true"></i>) }
</div>

The mapper assigns a key from the second argument (index) to each child element.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.