Conditional Handler Based On Slug In React Router?
I am new to react. I am using React Route and I would like to know if it's possible to execute a different handlers based on a slug passed to the route. For example I have the foll
Solution 1:
Remember that React/JSX gives you the full power of JavaScript. That means your route handler component can do whatever it wants--including rendering children conditionally. Something like this may work (I haven't run this, so consider it pseudocode):
var slugsToHandlers = {
'about': AboutPage,
'jobs': JobsPage,
};
var SlugRouteComponent = React.createClass({
contextTypes: {
router: React.PropTypes.func
},
render: function() {
var slug = this.context.router.getCurrentParams().slug;
var Handler = slugsToHandlers[slug] || NotFundPage;
return <Handler {...this.props} />;
}
});
// ...
<Route name="page" path="/:slug" handler={SlugRouteComponent} />
You could also, if you wanted, list each route individually:
<Route name="aboutPage" path="/about" handler={AboutPage} />
<Route name="jobsPage" path="/jobs" handler={JobsPage} />
<Route name="page" path="/:slug" handler={NotFoundPage} />
Post a Comment for "Conditional Handler Based On Slug In React Router?"