Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
Self-closing element conditional element using only one line?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

<>
  {
    React.createElement(flag? Comp1 : Comp2, { att1: attValue }, null)
  }
</>
about 4 years ago · Juan Pablo Isaza Report

0

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} />}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!