Home > Software design >  add prop base on condition to react component?
add prop base on condition to react component?

Time:12-08

<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.

CodePudding user response:

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

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

<MyComponent {...conditionalProps} />

CodePudding user response:

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

CodePudding user response:

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

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