How to repeat displaying something in JSX

By

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.

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

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

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>

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.

Tagged: React · All topics
~~~

Related posts about react: