Be the first user to complete this post

  • 0
Add to List

Pass props to the handler component in react-router

react-router has pretty much emerged as a clear winner when it comes to routing libraries for React. However, as you would have already noticed, there isint a very clear way on how to pass down props to your route handlers. For example, in the following setup, the top level component - App, simply renders whatever children are configured as per the route.

const App = React.createClass({
    displayName: 'App',

    render() {
        return this.props.children;
    }
});

const Index = React.createClass({
    displayName: 'Index',

    render() {
        return <div>Welcome</div>;
    }
});

React.render((
    <Router history={history}>
        <Route path="/" component={App}>
            <IndexRoute component={Index} />
        </Route>
    </Router>
), document.getElementById('app'));
Now, what if the Index component needs a prop to render?
const Index = React.createClass({
    displayName: 'Index',

    propTypes: {
        appName: React.PropTypes.string.isRequired
    },

    render() {
        return <div>Welcome to {this.props.appName}</div>;
    }
});
In the above case, the parent App.jsx needs to pass down a required prop to its child. The way to achieve this in react-router is by using React.cloneElement in App.jsx.
const App = React.createClass({
    displayName: 'App',

    render() {
        return React.cloneElement(
            this.props.children,
            {appName: 'Foo'}
        );
    }
});



Also Read:

  1. Execution sequence of a React component's lifecycle methods
  2. Using context and childContext in React
  3. Generating container components with connect utility in react redux app
  4. Pass down props using React childContextTypes in a deeply nested component tree
  5. Pure vs Impure functions
  6. Require the css file of a package using webpack
  7. webpack with babel6 and react