Andrew
Andrew

Reputation: 7545

Rendering <select> and <option> in separate components

I'm not entirely sure how references work when select and option are used together, but splitting them up into separate React components causes them to not work. How can I get this to work?

Basic example:

<select>
    {() => (
        <React.Fragment>
            <option>I do not render</option>
            <option>I not render as well</option>
        </React.Fragment>
    )}
</select>

React.Fragment is mandatory, because components can only render one entity. I was considering/ playing around with React.createRef, but ultimately I don't know how things work under the hood.

code sandbox: https://codesandbox.io/s/quirky-thompson-s452i

Upvotes: 0

Views: 70

Answers (1)

norbitrial
norbitrial

Reputation: 15166

The reason behind that is because you are technically just create an arrow function with:

() => (
   <React.Fragment>
      <option>I do not render</option>
      <option>I not render as well</option>
   </React.Fragment>
) 

So below you are calling the defined function as well.

If you change it like the following, it will render the options:

<select>
     {
         (() =>
            <React.Fragment>
               <option>I do not render</option>
               <option>I not render as well</option>
            </React.Fragment>
         )()
     }
</select>

The second technique is called IIFE, as the documentation states:

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.

Read further here: https://developer.mozilla.org/en-US/docs/Glossary/IIFE

Code sandbox:

Please find it here: https://codesandbox.io/s/mystifying-bas-p4ik9

I hope that helps!

Upvotes: 1

Related Questions