Search code examples
reactjsjsxternary

How can I combine a React element and text inside a ternary?


Normally if you have something like:

<SomeComponent foo={bar} />

you can make it optional by using a ternary:

{bar ? <SomeComponent foo={bar} /> : null}

But what if the block you are starting with contains a component plus some text (a single space) and a variable, e.g.:

<SomeComponent foo={bar} /> {foobar}

Wrapping it in parentheses won't work:

{bar ? (<SomeComponent foo={bar} /> {foobar}) : null}

and in fact the only way I found to make it work was to wrap everything in another element:

{bar ? <span><SomeComponent foo={bar} /> {foobar}</span> : null}

Is there any other way to tell React that:

<SomeComponent foo={bar} /> {foobar}

is a discrete chunk, so that I can use it in a ternary (inside JS, not JSX, logic) ... without adding meaningless wrapper elements?


Solution

  • There used to be two suboptimal ways to achieve this:

    1. Using an array, which requires adding keys to React elements:

      {bar ? [<SomeComponent key="1" foo={bar} />, " ", foobar] : null}
      
    2. Creating a wrapper component, like @margaretkru suggested.

    But with React 16.2.0+ you can use improved fragments:

    {bar ? <React.Fragment><SomeComponent foo={bar} /> {foobar}</React.Fragment> : null}
    

    or, even better, you can use the shorthand syntax:

    {bar ? <><SomeComponent foo={bar} /> {foobar}</> : null}
    

    Fragments won't produce an additional container element.