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,
};
varSlugRouteComponent = React.createClass({
contextTypes: {
router: React.PropTypes.func
},
render: function() {
var slug = this.context.router.getCurrentParams().slug;
varHandler = slugsToHandlers[slug] || NotFundPage;
return<Handler {...this.props} />;
}
});
// ...<Routename="page"path="/:slug"handler={SlugRouteComponent} />
You could also, if you wanted, list each route individually:
<Routename="aboutPage"path="/about"handler={AboutPage} /><Routename="jobsPage"path="/jobs"handler={JobsPage} /><Routename="page"path="/:slug"handler={NotFoundPage} />
Post a Comment for "Conditional Handler Based On Slug In React Router?"