Skip to content

Instantly share code, notes, and snippets.

@jdlehman
Last active April 10, 2017 07:26
Show Gist options
  • Save jdlehman/b662cac8b8607abf51a6 to your computer and use it in GitHub Desktop.
Save jdlehman/b662cac8b8607abf51a6 to your computer and use it in GitHub Desktop.
react-router: Define multiple route definitions such that components can respond to routes independently with their own RouteHandler
var React = require('react');
var Router = require('react-router'); // 0.12.4
var {Route, DefaultRoute, RouteHandler, Link, NotFoundRoute} = Router;
/* Components */
var App = React.createClass({
render: function () {
return (
<div className="App">
<div id="header"></div>
<div>content</div>
<div id="footer"></div>
</div>
);
}
});
var Header = React.createClass({
render: function () {
return <p>This is the header:<RouteHandler/></p>;
}
});
var Footer = React.createClass({
render: function () {
return <p>This is the footer:<RouteHandler/></p>;
}
});
var Default = React.createClass({
render: function() {
return <span>default view</span>;
}
});
var HeaderView1 = React.createClass({
render: function() {
return <span>header view one</span>;
}
});
var FooterView1 = React.createClass({
render: function() {
return <span>footer view one</span>;
}
});
var Null = React.createClass({
render: function() {
return false;
}
});
React.render(<App/>, document.body);
/* Routes */
var headerRoutes = (
<Route name="header" path="/" handler={Header}>
<Route name="view1" handler={HeaderView1}/>
<DefaultRoute handler={Default}/>
<NotFoundRoute handler={Null}/>
</Route>
);
Router.run(headerRoutes, function (Handler) {
React.render(<Handler/>, document.getElementById('header'));
});
var footerRoutes = (
<Route name="footer" path="/" handler={Footer}>
<Route name="view1" handler={FooterView1}/>
<DefaultRoute handler={Default}/>
<NotFoundRoute handler={Null}/>
</Route>
);
Router.run(footerRoutes, function (Handler) {
React.render(<Handler/>, document.getElementById('footer'));
});
@jdlehman
Copy link
Author

This pattern allows multiple components to respond differently to the same route.

In this example, the Header component and Footer component can both respond to routes independently as they each have their own RouteHandler and defined routes.

So on / both Header and Footer render Default in their RouteHandler, while on /view, Header's RouterHandler displays HeaderView1 and Footer's RouteHandler displays FooterView1.

@jdlehman
Copy link
Author

In case anyone stumbles upon this, here is a better solution for different parts of the view reacting to different routes. (it's also router agnostic!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment