0

Is there a way to pass props from the Parent component down to the Child component using react-router?

<Route path="/parent/" component={Parent} />
<Route path="/parent/child/" component={Child} />

Notice Child is not rendered in the Parent's render function.

Thanks

shell
  • 1,867
  • 4
  • 23
  • 39
  • Why do you have a hierarchy like this in the first place? – Andrew Li Jul 11 '18 at 03:34
  • Maybe its a dumb idea, but I had components that were consistent across all child route of parent (such as header, footer) rendered in parent. That way it didn't have to re-render on all child route changes. – shell Jul 11 '18 at 03:52
  • So you should use a Route within Parent. See https://stackoverflow.com/questions/41474134/nested-routes-with-react-router-v4 – Andrew Li Jul 11 '18 at 03:54

1 Answers1

1

I think a good solution here would be nested routes with render props.

// Parent.jsx

render() {
  const { match: { url }, xyz } = this.props;
  return (
    <Route path={`${url}/child`} render={() => <Child xyz={xyz} />}
  );
}
Sukrit
  • 308
  • 2
  • 12
  • In your example, how would I pass parent state into the component, such that when the Parent's state changes the component would be updated (i.e. it would receive the parent's state changes as props) – shell Jul 11 '18 at 05:15
  • So instead of extracting xyz from this.props you could extract any values from state too and pass them down to – Sukrit Jul 11 '18 at 05:22
  • Ah, I implemented a custom componentWillUpdate(nextProps, nextState), the problem was my component was not updating with some new state in some cases. – shell Jul 11 '18 at 05:29