Skip to content

Instantly share code, notes, and snippets.

@emilong
Created May 27, 2016 20:35
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emilong/3593d3de456f6f5120ef80afb8a4ebf3 to your computer and use it in GitHub Desktop.
Save emilong/3593d3de456f6f5120ef80afb8a4ebf3 to your computer and use it in GitHub Desktop.
Creating semantic links for react-router using HOCs
import React, { Component } from 'react'
import { SubWidgetLink } from './routes'
export default class MyComponentWithALink extends Component {
render() {
const { widget } = this.props
return (
<div>
...
<SubWidgetLink widgetId={widget.id}>All the subwidgets for {widget.name}</SubWidgetLink>
<SubWidgetLink widgetId={widget.id} subWidgetId={widget.bestSubWidget.id}>The best subwidget of {widget.name}</SubWidgetLink>
...
</div>
)
}
}
import React, { PropTypes } from 'react'
import { setPropTypes } from 'recompose'
import { Link } from 'react-router'
import Root from './root'
import { Activity } from './activity'
import { WidgetRoot, WidgetIndex } from './widget'
import { SubWidgetRoot, SubWidgetIndex } from './subwidget'
// a high-order component for creating semantic link components
const linkTo = (pathMapper, propTypes={}) => {
return setPropTypes(propTypes)(props => <Link to={pathMapper(props)}>{props.children}</Link>)
}
export const ActivityFeedLink = linkTo(() => '/activity')
export const WidgetLink = linkTo(props => `/widgets/${props.widgetId}`, {
widgetId: PropTypes.number.isRequired, // required, no collection available
})
export const SubWidgetLink = linkTo(props => `/widgets/${props.widgetId}/subwidgets/${props.subWidgetId}`, {
widgetId: PropTypes.number.isRequired,
subWidgetId: PropTypes.number, // optional. links to the collection without it.
})
export default (
<Route path='/' component={Root}>
<Route path='activity' component={Activity}>
<Route path='widgets/:widgetId' component={WidgetRoot}>
<IndexRoute component={WidgetIndex}/>
<Route path='subwidgets/:subWidgetId' component={SubWidgetRoot}>
<IndexRoute component={SubWidgetIndex}/>
</Route>
</Route>
</Route>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment