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
  • 46,070
  • 7
  • 44
  • 60
Mike K
  • 5,940
  • 7
  • 37
  • 87

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
  • 46,070
  • 7
  • 44
  • 60
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,411
  • 2
  • 6
  • 18