Home > Software design >  Passing a spread object as a prop on a conditional basis
Passing a spread object as a prop 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 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)} />

CodePudding user response:

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>

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

CodePudding user response:

chick if there is primaryProps then asign it to a new object props otherwise take the secondaryProps.


const props = !!primaryProps ? primaryProps : secondaryProps;

 <Component
    {...props}
 />

  • Related