Shadrech
Shadrech

Reputation: 473

Passing props to children components with react-router v4

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?

Upvotes: 4

Views: 1440

Answers (1)

Alexander Gundermann
Alexander Gundermann

Reputation: 286

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.

Upvotes: 3

Related Questions