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

Usually if you have something like:

<SomeComponent foo={bar} />

you can make this optional using triple:

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

But what if the block you start with contains a component plus some text (one space) and a variable, for example:

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

A wrapper in parentheses will not work:

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

and in fact, the only way to make it work is 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 piece, so I can use it in ternary (inside JS, not JSX, logic) ... without adding meaningless shell elements?

+4
source share
2 answers

To achieve this, there were two suboptimal methods:

  • , React:

    {bar ? [<SomeComponent key="1" foo={bar} />, " ", foobar] : null}
    
  • -, @margaretkru.

React 16.2.0+ :

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

, , :

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

.

+3

, , - , . , Aux:

const Aux = (props) => (props.children);

:

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

, , html, , flex-box, .

+2

Source: https://habr.com/ru/post/1691832/


All Articles