Reputation: 437
This one of the few examples i saw to pass props to routes, but i cant seem to get it to work
<Route path="/" render={()=><testPage num="2" someProp={100}/>}/>
The below example it was throwing me errors because "toggle" was undefined?
const MyProductPage = (props) => {
return (
<ProductPage
toggle={this.toggle.bind(this)}
{...props}
/>
);
}
Heres another one:
<Route path="/path" render={(props) => <Component {...props} Props={} />} />
What does {...props} mean in this case? Where do I put in my component? Please explain I really want to understand thanks! :)
Upvotes: 1
Views: 79
Reputation: 744
Well, for your MyProductPage component, using this
here is incorrect. MyProductPage is a functional component, not a class component.
Because props
is being passed down like an argument, you can access it like you can with any other argument.
So, the below code shouldn't pass an error... however, without knowing more about your code, I'm not sure where you need the toggle
method to be bound.
const MyProductPage = (props) => {
return (
<ProductPage
{...props}
toggle={props.toggle}
/>
);
}
Side note: I'm also pretty sure that {...props}
needs to be listed first. See below.
If you're continuing to have an issue with toggle
returning undefined behavior, then you'll probably need to change the lexical binding of this
higher up in the parent component. It just won't work if you set it here.
As for your second question, {...props}
is an example of the spread operator. The React-friendly definition can be found here.
To the change the example slightly:
var exampleObject= {};
exampleObject.foo = x;
exampleObject.bar = y;
var component = <Component {...exampleObject} />;
... the spread operator is just saying, take all of the methods from exampleObject
, and pass them down as props. It's another way of saying:
<Component foo={exampleObject.foo} bar={exampleObject.bar} />
This takes everything in exampleObject
and passes it down.
Imagine if you had 20 properties you want to pass down into a child component. That could get wordy pretty quickly, so the spread operator is just a bit of syntatic sugar so that you don't have to write it all out.
EDIT: To further tie this in with your examples:
Image if the parent component is passing props down like this:
<MyProductPage {...exampleObject} />
// Includes .foo and .bar
Then, if you don't need to change any of the stored values, the child component can just look this
const MyProductPage = (props) => {
return (
<ProductPage {...props} />
);
}
// still contains .foo and .bar
But, if you DO need to change one of the poperties, then, you simply pass it down separately (sort of like an "override"):
const MyProductPage = (props) => {
return (
<ProductPage
{...props}
foo={props.foo + 1}
/>
);
}
// still contains .foo and .bar, but foo will be different.
{...props}
first passes everything down, then, your explicit calling of foo
overrides what gets passed down and gives it a new value.
Upvotes: 1