Reputation: 3070
One can pass props to a component of a child route (while using React Router) by passing the props to the Route
component for the child component and accessing it in the child component of this route by this.props.route.propName
.
What about the props needed in a child component is a portion of the state of its parent component and not just some unrelated data to the components?
Since
in <Router />
the state of a parent App
is not in scope, one cannot pass it to component in a sub <Route />
, or
all reference to a child component in the parent component is {this.props.children}
and not <aComponent data={this.state.somePortion} />
, one, again, cannot pass it through the syntax of expression {this.props.children}
.
What is the catch?
Upvotes: 1
Views: 1754
Reputation: 2469
Update: Instead of store state within App
, your state will need to be stored in the component that is rendering the routes then passed to the route. You can use the method below to wrap the component if you want it to maintains it current propType list.
If you cannot use this.props.route.propName
another option would be to use an High-Order Component (HOC) that wraps your component and use it on the route, then pass the route props to the component you want to render.
const WrappedComponent = ({route}) => {
return (<Component data={route.data} />);
};
You could then further extensibility you could pass the component to render to the route as well.
<Route to='/about' component={WrappedComponent} data={[]} page={AboutPage} />
Then update wrapped to something like this:
const WrappedComponent = ({ route }) => {
const { page:Component, ...rest } = route;
return <Component {...rest} />;
};
This uses some ES2015+ with the rest operator, but would allow more reuse on this HOC.
Upvotes: 1