I'm trying to provide multiple optional attributes between components in React.
Example:
File: GenericCard.js
...
<Reactstrap.CardHeader {...this.props.headerArgs}>{this.props.cardheader}</Reactstrap.CardHeader>
<Reactstrap.CardBody {...this.props.bodyArgs}>{this.props.cardbody}</Reactstrap.CardBody>
<Reactstrap.CardFooter {...this.footerArgs}>{this.props.cardfooter}</Reactstrap.CardFooter>
...
I'm passing the props to this component as follow:
File: SpecificCard.js
<GenericCard cardheader={header} cardbody={body} cardfooter={footer} {...bodyArgs} />
And for example a different variant would be:
File: DifferentCard.js
<GenericCard cardheader={header} cardbody={body} cardfooter={footer} {...headerArgs} {...footerArgs} />
But such syntax would provide me with:
Uncaught ReferenceError: {the attribute that's missing} is not defined
Meaning, I'd like to be able to pass multiple options for different attributes using spread arguments, and were they to be not defined, I'd like the props to ignore them (as I understand that is the case for normal props?).
I thought of putting a default value, but I can't seem to find how to achieve that.
Any help would be much appreciated.
Edit:
I tried replacing my code as per @SteveTomlin suggestion:
File: SpecificCard.js
{...{...headerArgs, ...bodyArgs, cardbody: body, cardheader: header}}
After doing some debugging I realized that the issue was that the spread variables were passing the attributes themselves and not the variables, meaning I can't distinguish between the different variables when receiving it on GenericCard.js
. Explanation in code:
File: SpecificCard.js
const body = <div>a</div>;
const bodyArgs = {attributeA: 'a', attributeB: 'b', attributeC: 'c'};
When I receive it on GenericCard.js
the props looks like:
cardbody: "<div>a</div>"
attributeA: 'a'
attributeB: 'b'
attributeB: 'c'
So I don't have the bodyArgs
as props but rather its attributes.
I tweaked Steve's suggestion to look like this:
{...{headerArgs: headerArgs, bodyArgs: bodyArgs, footerArgs: footerArgs, cardheader:header, cardbody:body, cardfooter:footer}}
Which then works fine, but necessitates defining all the variables on the parent component, which is not what I was aiming at. What I'm looking for is a way to do exactly that, but without having to define the empty variables (again, as I understood React works in the link above). Something like this should work in the solution just the same as the code above:
{...{headerArgs: headerArgs, cardheader:header, cardbody:body, cardfooter:footer}}
Can this sort of props behavior work? How can I do that? Shouldn't the child props ignore missing props? If not, can I put default values on the child component?