Created
May 27, 2016 20:35
-
-
Save emilong/3593d3de456f6f5120ef80afb8a4ebf3 to your computer and use it in GitHub Desktop.
Creating semantic links for react-router using HOCs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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