1
votes

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?

1
Have you looked at redux/flux? Would probably help you solve this issue much easierA. L
Yes I have looked at them. Because the redux store in upper in the main component and provided by a <Provider/>component in binding library react-redux all the components in the Router hierarchy can be fed by state by passing as props and accessing in component with this.props.route.propName. Thanks. But applying redux to my set up seems a bit difficult to me. Any solution without it. There MUST be some way, and not cumbersome too much.sçuçu
Making use of some utilizers to make the life easier sometimes makes you loose some easiness, to regain that lost bits you need another construct that is potentially limit you in another little to big way. Using React Router makes the state in top component un-passable to the children components in this case for me for now. How I will make data flow down the way through components, ideally with props in React.js. Right? There must be some easy plain way.sçuçu

1 Answers

1
votes

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.