Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Last active February 2, 2018 22:01
Show Gist options
  • Save ryanflorence/277b8145eea9d53458ca40436f46aeb7 to your computer and use it in GitHub Desktop.
Save ryanflorence/277b8145eea9d53458ca40436f46aeb7 to your computer and use it in GitHub Desktop.
Rail-ey style routes
const lookup = (namespace) => {
// if you really want rails-style indirection, you'd
// need an app container that could look up modules
// by strings.
}
const Resources = ({ namespace }) => {
const Layout = lookup(namespace, 'layout')
return (
<Route path={`/${namespace}`} render={() => (
<Layout>
<Switch>
<Route exact path={`/${namespace}`} component={lookup(namespace, 'index')}/>
<Route exact path={`/${namespace}/:${camelize(namespace)}Id`} component={lookup(namespace, 'show')}/>
<Route exact path={`/${namespace}/:${camelize(namespace)}Id/edit`} component={lookup(namespace, 'edit')}/>
</Switch>
</Layout>
)}/>
)
}
ReactDOM.render((
<BrowserRouter>
<div>
<Resources namespace="posts"/>
<Resources namespace="users"/>
<Resources namespace="comments"/>
</div>
</BrowserRouter>
), el)
@ryanflorence
Copy link
Author

Sorry, I swapped out the <div/> for a <Switch/> last minute to make it more generic looking, should be fine w/o the Switch (I updated the gist).

@ryanflorence
Copy link
Author

It would be nice if you could pass a custom matcher function to switch actually.

Switch is so tiny, I think it's just as well to just say "copy/paste/tweak for your needs" instead of us opening up some API that's hard for us to predict its effects right now.

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Switch.js#L33-L50

@matthewrobb
Copy link

matthewrobb commented Mar 21, 2017

I think it's just as well to just say "copy/paste/tweak for your needs"

I actually agree with this. Open to a PR against the docs showing a custom Switch implementation for the Modal example :D ?

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