Repeatedly render an element 5 times in React.js?

Answered
yaboy01 asked this question 1 year, 5 months ago
yaboy01 on Jan 4, 2022

In my React.js application, I'm trying to render an element repeatedly 5 times. And the amount of times it needs to be repeated sometimes changes based on outside conditions.

The element is a simple <div> element:

<div>
  <span>My Element</span>
</div>

In my React.js application, I need that element to repeat 5 times.

How can I do that?

2 suggested answers
itsbambi on Jan 14, 2022 · Edited

Try this:

{
  [...Array(5)].map((item, index) => {
    return (
      <div key={index}>
        <span>My Element</span>
      </div>
    )
  })
}

This will render the div 5 times. Replace 5 in that code with whatever count you want.

0 replies
nick on Jan 14, 2022

Simple way:

render() {
  return (
    <>
      {
         Array.apply(null, { length: 5 }).map((item, i) => {
           return (
             <div key={i}>My Element</div>
           )
         })
       }
    </>
  )
}
0 replies
Answered