Created
October 14, 2015 08:13
-
-
Save pekkis/11f6e3bca2f944b5050f to your computer and use it in GitHub Desktop.
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 from 'react'; | |
function getDisplayName(Component) { | |
return Component.displayName || Component.name || 'Component'; | |
} | |
function isLeftClickEvent(event) { | |
return event.button === 0; | |
} | |
function isModifiedEvent(event) { | |
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); | |
} | |
export function wrapper(Component) { | |
class Wrapper extends React.Component { | |
static displayName = `Wrapper(${getDisplayName(Component)})`; | |
static propTypes = { | |
active: React.PropTypes.bool, | |
disabled: React.PropTypes.bool, | |
href: React.PropTypes.string.isRequired, | |
query: React.PropTypes.object, | |
onClick: React.PropTypes.func | |
}; | |
static defaultProps = { | |
activeClassName: 'active' | |
}; | |
static contextTypes = { | |
history: React.PropTypes.object.isRequired | |
}; | |
constructor(props, context) { | |
super(props, context); | |
} | |
render() { | |
return <Component {...this.getLinkProps()} /> | |
} | |
/** | |
* Returns props except those used by this Mixin | |
* Gets "active" from router if needed. | |
* Gets the value of the "href" attribute to use on the DOM element. | |
* Sets "onClick" to "handleRouteTo". | |
*/ | |
getLinkProps() { | |
const { | |
href, | |
query, | |
...props | |
} = this.props; | |
console.log(props, 'da props'); | |
if (this.props.active === undefined) { | |
props.active = this.context.history.isActive(href, query); | |
} | |
props.href = this.context.history.createHref(href, query); | |
props.onClick = this.handleRouteTo.bind(this); | |
return props; | |
} | |
handleRouteTo(event) { | |
let allowTransition = true; | |
let clickResult; | |
if (this.props.disabled) { | |
event.preventDefault(); | |
return; | |
} | |
if (this.props.onClick) { | |
clickResult = this.props.onClick(event); | |
} | |
if (isModifiedEvent(event) || !isLeftClickEvent(event)) { | |
return; | |
} | |
if (clickResult === false || event.defaultPrevented === true) { | |
allowTransition = false; | |
} | |
event.preventDefault(); | |
if (allowTransition) { | |
this.context.history.pushState(this.props.state, this.props.href, this.props.query) | |
} | |
} | |
}; | |
return Wrapper; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment