Finalmix6
Finalmix6

Reputation: 415

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 :

  <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

Upvotes: 0

Views: 508

Answers (2)

Shan
Shan

Reputation: 1568

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

Upvotes: 2

Ubaid Hussain
Ubaid Hussain

Reputation: 105

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

Wrap you options like this

Upvotes: 2

Related Questions