How to repeat displaying something in JSX

By

Published · Updated

Tagged: React

Learn how to repeat an element in JSX with Array.from(), including a stable key for each generated React element.

I had the need to repeat something in JSX.

The use case was this, I had a review expressed from 1 to 5 and based on the value I wanted to display some stars, from 1 to 5 stars.

JSX has no loop syntax, and there’s no for you can put inside the markup. You need an expression that gives back an array (or a string), and React renders each item.

Repeat a string with repeat()

If I only need the text, I can use repeat():

<p>{'⭐️'.repeat(rating)}</p>

Repeat an element with Array.from()

To render a React element for every item, use Array.from():

<p aria-label={`${rating} out of 5 stars`}>
  {Array.from({ length: rating }, (_, index) => (
    <span aria-hidden="true" key={index}>⭐️</span>
  ))}
</p>

Array.from({ length: rating }) creates an array with rating items, and the second argument is a function that runs for each one, like map(). The first parameter is the item (here always undefined, so I call it _), the second is the index.

The aria-label gives screen readers “3 out of 5 stars”, and aria-hidden on the stars stops them from reading out every single star.

Why Array(5).map() renders nothing

You might try this instead:

<p>{Array(5).map((_, index) => <span key={index}>⭐️</span>)}</p>

It renders an empty <p></p>, with no error. Array(5) creates an array with a length of 5 but no actual items (a “sparse” array), and map() skips the missing items, so the function never runs.

Spreading it into a new array fills it with undefined values, and then map() works:

<p>{[...Array(5)].map((_, index) => <span key={index}>⭐️</span>)}</p>

Both this and Array.from() work. Array.from() does it in one step, without creating the extra array.

Show filled and empty stars

A rating usually shows all 5 stars, with some filled and the others empty. Loop over the maximum, and pick the star based on the index:

function Stars({ rating, max = 5 }) {
  const filled = Math.max(0, Math.min(max, Math.round(rating)))

  return (
    <p aria-label={`${filled} out of ${max} stars`}>
      {Array.from({ length: max }, (_, index) => (
        <span aria-hidden="true" key={index}>
          {index < filled ? '★' : '☆'}
        </span>
      ))}
    </p>
  )
}

<Stars rating={3} /> renders ★★★☆☆.

The Math.round() and the Math.max() / Math.min() keep the value between 0 and 5, so a rating of 4.6 shows 5 stars, and -2 or 9 don’t break the layout.

Edge cases: decimals, negative numbers, missing values

Ratings often come from an API or a form, so they’re not always a clean integer. This is what happens with each approach:

rating'⭐️'.repeat(rating)Array.from({ length: rating })
3.53 stars3 stars
'3'3 stars3 stars
undefinednothingnothing
-1throws RangeError: Invalid count value: -1nothing

Decimals are rounded down, not to the nearest number. And repeat() with a negative number crashes the whole component, so clamp the value like in the Stars component above before you use it.

Keys

Using the array index as a key is fine in this example because the stars have no independent state and their order never changes. For a real list whose items can be inserted, removed, or reordered, use a stable ID from the data instead.

If you forget the key, the stars still render, but React logs a warning in the console in development:

Each child in a list should have a unique "key" prop.

If each repetition needs more than one element and no wrapper, use Fragment with a key. The short <>...</> syntax can’t take a key:

import { Fragment } from 'react'

<dl>
  {Array.from({ length: 3 }, (_, index) => (
    <Fragment key={index}>
      <dt>Question {index + 1}</dt>
      <dd>Answer {index + 1}</dd>
    </Fragment>
  ))}
</dl>

To loop over an array of data instead of a number, see how to loop inside React JSX.

Want me to talk about your product? You can sponsor this site.

Related posts about react: