Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
@matthewrobb

This comment has been minimized.

Copy link

@matthewrobb matthewrobb commented Mar 21, 2017

This doesn't actually work for me @ryanflorence. Reason being that unless something has changed, <Switch/> naively checks the props of it's children before rendering them and it checks against a "path" prop that would have needed to be passed down. Returning a <Route/> from a component doesn't have this effect.

@matthewrobb

This comment has been minimized.

Copy link

@matthewrobb matthewrobb commented Mar 21, 2017

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

@ryanflorence

This comment has been minimized.

Copy link
Owner Author

@ryanflorence ryanflorence commented Mar 21, 2017

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

This comment has been minimized.

Copy link
Owner Author

@ryanflorence ryanflorence commented Mar 21, 2017

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

This comment has been minimized.

Copy link

@matthewrobb 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
You can’t perform that action at this time.