Home > Back-end >  Self-closing element conditional element using only one line?
Self-closing element conditional element using only one line?

Time:06-25

I would like to render a component out of two depending on a flag value. I was wondering if there is a way to do this in only one line?

I was thinking something like this: <(flag ? Comp1 : Comp2) att1={attValue} ... />

If there is not a way, is it possible to somehow add it as a feature in the future?

CodePudding user response:

You can interpolate a React.createElement that alternates between the two components.

<>
  {
    React.createElement(flag? Comp1 : Comp2, { att1: attValue }, null)
  }
</>

CodePudding user response:

I know 2 ways of doing this the JSX way. Even though they all require more than one line, I think they are still DRY and help you avoid errors from code duplication. This goes without saying, but your components must receive the same props for these approaches to work.

The first one is to create a variable for your desired component, then render it (note that this variable name must start with an uppercase letter).

const YourComp = flag ? Comp1 : Comp2;

<YourComp att1={attValue} ... />

The second way is to create a variable for your props, then spread it:

const props = {
  attr1: attrValue,
  ...
}

{flag ? <Comp1 {...props} /> : <Comp2 {...props} />}
  • Related