Kosmetika Kosmetika - 6 months ago 106
Javascript Question

react-router - pass props to handler component

I have such structure of my React.js app with ReactRouter (https://github.com/rackt/react-router):

var Dashboard = require('./Dashboard');
var Comments = require('./Comments');

var Index = React.createClass({
render: function () {
return (
<div>
<header>Some header</header>
<RouteHandler />
</div>
);
}
});

var routes = (
<Route path="/" handler={Index}>
<Route path="comments" handler={Comments}/>
<DefaultRoute handler={Dashboard}/>
</Route>
);

ReactRouter.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});


I want to pass some properties into
Comments
component

(normally like
<Comments myprop="value" />
)

What's the easiest and right way to do so with ReactRouter?

Answer

Preferred way is wrap Comments component and pass wrapper as route handler.

This is your example with changes applied:

var Dashboard = require('./Dashboard');
var Comments = require('./Comments');

var CommentsWrapper = React.createClass({
  render: function () {
    return (
        <Comments myprop="myvalue" />
    );
  }
});

var Index = React.createClass({
  render: function () {
    return (
        <div>
            <header>Some header</header>
            <RouteHandler />
        </div>
    );
  }
});

var routes = (
  <Route path="/" handler={Index}>
    <Route path="comments" handler={CommentsWrapper}/>
    <DefaultRoute handler={Dashboard}/>
  </Route>
);

ReactRouter.run(routes, function (Handler) {
  React.render(<Handler/>, document.body);
});