Search code examples
javascriptreactjsreact-routerreact-router-component

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?


Solution

  • 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.