Home > Net >  Passing two spread objects as props on a conditional basis
Passing two spread objects as props on a conditional basis

Time:03-08

I have a component which is currently taking in a object value as a prop which is being spread.

const primaryProps = {/* about 10 key/values in here */}

<Component
  {...primaryProps}
/>

This works as intended. But now I am try to add an OR to it and add another object which is spread. But this is throwing syntax errors. Is there a way around it? Thanks.

Tried following which doesn't work.

const primaryProps = {/* about 10 key/values in here. Can also be empty/null */}
const secondaryProps = {/* about 10 key/values in here */}

<Component
  {...primaryProps || ...secondaryProps}
/>


<Component
  `${primaryProps.join(",") || secondaryProps.join(",")}`
/>

CodePudding user response:

If I understood what you are trying to do, this would work :

<Component
  {...primaryProps} 
  {...secondaryProps}
/>

CodePudding user response:

I don't think this is possible to do inside the props of a component. Also it isn't clean. What would I suggest is take the condition out of the component.

const props = condition ? primaryProps : secondaryProps
<Component {...props} />
  • Related