1

I'm trying to map some elements based on an arbitrary length.

I haven't been able to find anything online, but I'd like to do something like:

new Array(5).map(num => <input />)

but this doesn't seem to work.

A user would input a number, and then that many input fields should render.

What am I doing wrong here?

CodeSandbox

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Mike K
  • 7,621
  • 14
  • 60
  • 120

2 Answers2

4

You need to fill the array before mapping, as map ignores empty slots.

new Array(5).fill().map(num => <input />)

However, Array.from would be more suitable in this case.

Array.from({length: 5}, ()=> <input />)
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

use fill then map the array

new Array(5).fill().map(num => <input />)

or you could use Array.from

Array.from(Array(5), ()=> <input />)
Sven.hig
  • 4,449
  • 2
  • 8
  • 18