简体   繁体   中英

Passing a spread object as a prop on a conditional basis

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(",")}`
/>

If you want to pass secondaryProps only when the primaryProps are null or undefined you can do it like that (but note that this will not work if the passed object is defined but empty):

<Component {...(primaryProps ?? secondaryProps)} />

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

Your attempt:

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

Won't work because you don't need to spread the secondaryProps .

If primaryProps is NULL secondaryProps will be used with the first spread syntax


So remove the second ... and use:

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

Small example, toggle primary to see it in action

 class Child extends React.Component { render() { return Object.values(this.props); } } class Example extends React.Component { render() { // const primary = { foo: 'primary' }; const primary = null; const secondary = { bar: 'secondary' }; return <Child {...primary || secondary } />; } } ReactDOM.render(<Example />, document.body);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM