Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React select dropdown from 1 to n

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading