hidace hidace - 1 year ago 99
Javascript Question

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.

Answer Source

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 (

edit: remember to add key to lists

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download