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

129
Views
add prop base on condition to react component?
<MyComponent something={somethingIsTrue} />

How to add something as prop to MyComponent if somethingIsTrue? I still wouldn't want something=undefined or something=false because it's still been added to MyComponent. I want it to be

not added as prop

if somethingIsTrue is falsely.

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

0

I have yet to try this but something like this should do the trick.

const conditionalProps = shouldHaveProps ? {something: somethingIsTrue} : {};

<MyComponent {...conditionalProps} />
about 4 years ago · Juan Pablo Isaza Report

0

You can make use of the dynamic expression in JSX for the desired result

<MyComponent {...(somethingIsTrue ? {something:somethingIsTrue} : {})}/>
about 4 years ago · Juan Pablo Isaza Report

0

1) You can do as:

Live Demo

Codesandbox Demo

const something = true;
const props = something ? { something: something } : null;
return <MyComponent {...props} />;

2) You can toggle component with pass argument if something is truthy

Live Demo

Codesandbox Demo

const something = true;

return something 
          ? <MyComponent something={something} /> 
          : <MyComponent />; 
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!