Created
March 11, 2017 11:56
-
-
Save marcgreenstock/fb47f0de50654f4c5d3e2f47cb106d74 to your computer and use it in GitHub Desktop.
React Router 4.0 LinkContainer
This file contains 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
'use strict' | |
import React, { Component, PropTypes, cloneElement } from 'react' | |
import { Route } from 'react-router-dom' | |
const isModifiedEvent = (event) => ( | |
!!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey) | |
) | |
export default class LinkContainer extends Component { | |
static propTypes = { | |
onClick: PropTypes.func, | |
target: PropTypes.string, | |
replace: PropTypes.bool, | |
to: PropTypes.oneOfType([ | |
PropTypes.string, | |
PropTypes.object | |
]).isRequired | |
} | |
static defaultProps = { | |
replace: false | |
} | |
static contextTypes = { | |
router: PropTypes.shape({ | |
history: PropTypes.shape({ | |
push: PropTypes.func.isRequired, | |
replace: PropTypes.func.isRequired, | |
createHref: PropTypes.func.isRequired | |
}).isRequired | |
}).isRequired | |
} | |
handleClick = (event) => { | |
if (this.props.onClick) { | |
this.props.onClick(event) | |
} | |
if ( | |
!event.defaultPrevented && // onClick prevented default | |
event.button === 0 && // ignore right clicks | |
!this.props.target && // let browser handle "target=_blank" etc. | |
!isModifiedEvent(event) // ignore clicks with modifier keys | |
) { | |
event.preventDefault() | |
const { history } = this.context.router | |
const { replace, to } = this.props | |
if (replace) { | |
history.replace(to) | |
} else { | |
history.push(to) | |
} | |
} | |
} | |
render () { | |
const { to, children, ...props } = this.props | |
const href = this.context.router.history.createHref( | |
typeof to === 'string' ? { pathname: to } : to | |
) | |
return ( | |
<Route | |
path={to} | |
{...props} | |
children={({match}) => { | |
const active = !!match | |
return cloneElement(children, { | |
href, | |
active, | |
onClick: this.handleClick | |
}) | |
}} /> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment