4

Previously in react-router v3.* I passed props to children components via

React.cloneElement(this.props.children, this.props)

How is this done in react-router v4 with the new <Match /> API

So far the solution I've come up with is to use the render method in the <Match /> API:

<Match pattern="/" render={() => <ChildComponent {...this.props} />} />

using the ES6 spread syntax to pass props to Child Component. Is there a better way which also carries with it all the standard props (location, pattern, pathname, isExact) to the child component?

Shadrech
  • 453
  • 4
  • 11

1 Answers1

3

Judging by the render code of v4.0.0-alpha5, you have the following two options:

<Match pattern="/" render={props => <ChildComponent {...props} {...this.props} />} />
<Match pattern="/">{({matched, ...props}) => {
    return matched ? <ChildComponent {...props} {...this.props} /> : null;
}}</Match>

Also see the Match API documentation.

  • I'm using react-router v4.0.0-2 as I'm not sure how stable the alpha versions are. I guess react-router v4 is still generally in development, I've noticed even that npm only ship v3 unless you explicitly ask for version 4 – Shadrech Nov 05 '16 at 20:49
  • It seems like the relevant rendering code is the same in alpha-2. But yeah, I think v4 is still very experimental. If you're looking for something stable, I'd use v3 instead. – Alexander Gundermann Nov 05 '16 at 21:06
  • Yh it is. Didn't realise props were arguments passed into render function. Thanks! This is probably the best solution at the moment – Shadrech Nov 07 '16 at 12:45