I have a textbox where user inputs a number which is stored in a state value
.
Now I want to create an array [0, 1, 2, ..., value]
.
This array will be used to create (value + 1)
number of boxes/divs each with their corresponding ids.
Now I've tried this
{(value) &&
([...Array(value).keys()].map(id => (
<NodeBox id={id} >
<h3>{id}</h3>
</NodeBox>
)))
}
But it created only one box with h3 text '0' in it. I have the state, the NodeBox, everything defined properly. There seems to be no problem with it.
If I do this
{(value) &&
([0, 1, 2, 3].map(id => (
<NodeBox id={id} >
<h3>{id}</h3>
</NodeBox>
)))
}
I get results as expected. I get 4 boxes containing the corresponding number.
I think that value is a string instead of a number.
When you use new Array()
or Array.from(), you look at the length of something instead of the actual value. So I think that value
is a string representing a number below 10, which would give it a length of 1, matching your output.
So I would use Array.from({ length: value }).map(( id, index ) => (<NodeBox id={index} >)
so that it does not matter if value is a string or a number.
The alternative would be to parse the string into a number before using it in Array(value)
.