Route Router Rehabilitation
I am using React Router for server side rendering and I would like to run a custom action on a specific route, actually on the DefaultRoute. How do I create a condition for this? I've tried the following code:
var React = require("react");
var Router = require("react-router");
var DefaultRoute = Router.DefaultRoute;
var Link = Router.Link;
var Route = Router.Route;
var RouteHandler = Router.RouteHandler;
var routes = [
React.createElement(Route, {name: "root", path: "/", handler: Root},
React.createElement(DefaultRoute, {handler: Default})
)
]
var Default = React.createClass({
displayName: "Default",
render: function () {
return React.createElement("h2", null, "Default");
}
});
var Root = React.createClass({
displayName: "App",
render: function () {
return (
React.createElement(RouteHandler, null)
);
}
});
app.get('*', function (req, res) {
Router.run(routes, req.path, function (Root, state) {
if (React.createElement(Root, null).constructor.displayName === 'Default'){
//run specific action
}
});
});
But I can't get the component name this way. Is there any other way to know that I'm on the default route?
+3
source to share
2 answers
I'm also using React-Router for isomorphic server side routing.
Support state
callback Router.run
contains active routes. You can do something like:
// states.routes returns the nested routes that your path matches.
// This will return the last route.
if (state.routes[state.routes.length-1].isDefault) {
// stuff here
// you also have access to the onEnter method and the handler (component) in the route too.
}
Check out the API documentation here: http://rackt.github.io/react-router/#Router.run . Good luck!
+1
source to share