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. Using React with Backbone Models
  2. Render a d3js Tree as a React Component
  3. Pass down props using React childContextTypes in a deeply nested component tree
  4. combineReducers in reduxjs explained