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 : display multiple hard coded options in Select component

How can I display multiple options tag in my Select component ?

Here’s my component :

  <Select
    id='myID'
    name='myName'>
      {
          (
              (localStorage.getItem("localStorageKey").includes("John"))
                  ?
                    <option key=1 value=myFirstValue>Option 1</option>
                  :
                    `
                      "Something else here"
                    `
          )
      }
  </Select>

So far if I put just one option it’s working, but if I add another one, say :

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

  <Select
    id='myID'
    name='myName'>
      {
          (
              (localStorage.getItem("localStorageKey").includes("John"))
                  ?
                    <option key=1 value=myFirstValue>Option 1</option>
                    +
                    <option key=2 value=mySecondValue>Option 2</option>
                  :
                    `
                      "Something else here"
                    `
          )
      }
  </Select>

It won’t display anything

>Solution :

In order to have more than one JSX element as sibling, It should be wrapped either in a React Fragment or in an array.

<> is a short hand for <React.Fragment>

<Select
  id='myID'
  name='myName'>
  {
    (localStorage.getItem("localStorageKey").includes("John"))
      ?
                  <>
                    <option key={1} value="myFirstValue">Option 1</option>
                    <option key={2} value="mySecondValue">Option 2</option>
                  </>
                  : "Something else here"
      }
</Select>

By using array,

[<option key={1} value="myFirstValue">Option 1</option>,
<option key={2} value="mySecondValue">Option 2</option>]
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