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. Pure vs Impure functions
  2. Generating container components with connect utility in react redux app
  3. Automating Store and Action registration for multiple components using Fluxxor
  4. Using context and childContext in React
  5. Reactjs flux architecture - Visualized