Skip to content

Instantly share code, notes, and snippets.

@c0d0g3n
Created July 29, 2017 13:21
Show Gist options
  • Save c0d0g3n/314689053535d73446917879f78e2356 to your computer and use it in GitHub Desktop.
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)
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