Home > Software design >  React select dropdown from 1 to n
React select dropdown from 1 to n

Time:11-09

I currently have a select dropdown that shows the numbers 1-10 like so

const options = [
        {
            label: 1,
            value: 1
        },
        {
            label: 2,
            value: 2
        },
        {
            label: 3,
            value: 3
        } // and so on and so forth
];

<select onChange={(e) => {handleChange(e)}}>
    {options.map((option) => (
         <option value={option.value}>{option.label}</option>
    ))}
</select>

But I instead would like to make the drop down instead of 1-10, 1- whatever the value of variable N is.

I am new to react and am not really sure what to try honestly.

CodePudding user response:

If you just mean that you want to generate a list of options inline from 1-N without having any backing data (i.e. no options array), you could do something like this:

<select onChange={handleChange}>
  {
    [...Array(10)].map((_, i) => i   1)
                  .map(i => <option key={i} value={i}>{i}</option>)
  }
</select>

This essentially:

  1. Creates an array of 10 elements (which could be any dynamic value you like)
  2. Calls .map() to fill it with integers (just using the index of each element 1 as its new value)
  3. And calls .map() on that to return the <option> elements

CodePudding user response:

would like to make the drop down instead of 1-10, 1- whatever the value of variable N is.

Array#slice it before mapping:

{options.slice(0, n).map(...)}
  • Related