Home > Mobile >  React : display multiple hard coded options in Select component
React : display multiple hard coded options in Select component

Time:05-02

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 :

  <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

CodePudding user response:

<>
  <option key=1 value=myFirstValue>Option 1</option>
  <option key=2 value=mySecondValue>Option 2</option>
</>

Wrap you options like this

CodePudding user response:

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>]
  • Related