Alicia Y
Alicia Y

Reputation: 387

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.

Upvotes: 3

Views: 444

Answers (3)

Mathews Sunny
Mathews Sunny

Reputation: 1642

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

<MyComponent {...(somethingIsTrue ? {something:somethingIsTrue} : {})}/>

Upvotes: 1

DecPK
DecPK

Reputation: 25408

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 />; 

Upvotes: 1

Rajesh Paudel
Rajesh Paudel

Reputation: 1135

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

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

<MyComponent {...conditionalProps} />

Upvotes: 2

Related Questions