I have the following structure for my React.js application using 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 the Comments
component.
(normally I'd do this like <Comments myprop="value" />
)
What's the easiest and right way to do so with React Router?
This is the solution from Rajesh, without the inconvenient commented by yuji, and updated for React Router 4.
The code would be like this:
Note that I use
render
instead ofcomponent
. The reason is to avoid undesired remounting. I also pass theprops
to that method, and I use the same props on the Comments component with the object spread operator (ES7 proposal).Copying from the comments by ciantic in the accepted response:
This is the most graceful solution in my opinion. It works. Helped me.
Wrap it with a stateless function component:
Just a follow-up to ColCh's answer. It is quite easy to abstract the wrapping of a component:
I haven't tested this solution yet so any feedback is important.
It's important to note that with this method, any props sent via the Router (such as params) get overwritten / removed.
Use the component with or without router based on Rajesh Naroth answer.
Or your could do it this way:
React-router v4 alpha
now there is a new way, to do this, although very similar to the previous method.
P.S. This works only in alpha version, and were removed after the v4 alpha release. In v4 latest, is once again , with the path and exact props.
react-lego an example app contains code that does exactly this in routes.js on its react-router-4 branch