Repeatedly render an element 5 times in React.js?

Answered
yaboy01 asked this question 21 days ago
yaboy01 21 days ago

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 11 days ago · 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 11 days ago

Simple way:

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