Last active
May 2, 2017 10:36
-
-
Save tarjei/2fc2dfe69f5a50d5945b1e745cc8f5eb to your computer and use it in GitHub Desktop.
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
import React from 'react' | |
import PropTypes from 'prop-types' | |
/** | |
* This is an implementation of React-Routes Link element that will render even if the context | |
* is missing the router object. | |
*/ | |
const isModifiedEvent = (event) => | |
!!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey) | |
/** | |
* The public API for rendering a history-aware <a>. | |
*/ | |
class Link extends React.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 | |
&& process.env.NODE_ENV !== 'test' | |
) { | |
event.preventDefault() | |
const { history } = this.context.router | |
const { replace, to } = this.props | |
if (replace) { | |
history.replace(to) | |
} else { | |
history.push(to) | |
} | |
} | |
} | |
render() { | |
const { replace, to, ...props } = this.props // eslint-disable-line no-unused-vars | |
const href = (process.env.NODE_ENV !== 'test') | |
? this.context.router.history.createHref(typeof to === 'string' ? { pathname: to } : to) | |
// if test then mock links | |
: typeof to === 'string' ? to : to.pathname | |
return <a {...props} onClick={this.handleClick} href={href}/> | |
} | |
} | |
export default Link |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment