Created
July 29, 2017 13:21
-
-
Save c0d0g3n/314689053535d73446917879f78e2356 to your computer and use it in GitHub Desktop.
Little HOC that stops event propagation (also prevents default behavior of link/button/... if `strict="true"` is passed)
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' | |
export default class MuteClicksComponent extends React.Component { | |
handleClick (childClickHandler) { | |
return (e) => { | |
e.stopPropagation() | |
// also prevent child link/button/... from working if neccesary | |
if (this.props.strict) e.preventDefault() | |
// pass control to original onClick handler | |
if (childClickHandler) childClickHandler(e) | |
} | |
} | |
render () { | |
const child = React.Children.only(this.props.children) | |
const {onClick, ...rest} = child.props | |
return React.cloneElement( | |
child, | |
{ | |
...rest, | |
onClick: this.handleClick(onClick).bind(this), | |
} | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment