I am using an array of 51 positions, the same one that I traverse with map but I need it to be displayed only from position 2 to the end in order to avoid index 0 and 1 being displayed.
This is my code:
<select
defaultValue={'DEFAULT'}
onChange={ (e) =>handlerPresentationSelected(e)}
className="border-solid border-2 border-slate-200 w-full p-2"
>
<option value="DEFAULT" disabled>Seleccione</option>
{ [...Array(51)].map( (value, index) => (
<option
key={index}
value={index}>
{ index }
</option>
))}
</select>
How can I achieve it? Thanks.
CodePudding user response:
<select
defaultValue={"DEFAULT"}
onChange={(e) => handlerPresentationSelected(e)}
className="border-solid border-2 border-slate-200 w-full p-2"
>
<option value="DEFAULT" disabled>
Seleccione
</option>
{[...Array.from({length: 49}, (_, i) => i 2)].map((value) => (
<option key={value} value={value}>
{value}
</option>
))}
</select>
CodePudding user response:
Maybe build an array in a function with a loop, and then call that within the JSX instead.
const { useState } = React;
function Example() {
// Create an array from 2 to 51
function getArray(n) {
const arr = [];
for (let i = 0; i <= n - 2; i ) {
arr[i] = i 2;
}
return arr;
}
return (
<div>
<select>
{getArray(51).map(n => {
return <option value={n}>{n}</option>
})}
</select>
</div>
);
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>