Search code examples
javascriptreactjsreact-routerurl-routingreact-router-component

React Router conditioning by Route


I'm using React Router for server side rendering and I'd like to run a special action on certain Route, actually on DefaultRoute. How should I create condition for that? I tried 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 name of component this way. Is there any other way to recognize that I'm on Default Route??


Solution

  • if (state.routes.length === 0 || state.routes[state.routes.length - 1].isDefault) { 
        // stuff here 
    }
    

    That's even better.