Last active
April 8, 2019 11:43
-
-
Save smitroshin/43cf4913e0c3def66301f6be3772b7f1 to your computer and use it in GitHub Desktop.
Click outside in React.js
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
class Popover extends React.Component { | |
constructor() { | |
super(); | |
this.handleClick = this.handleClick.bind(this); | |
this.handleOutsideClick = this.handleOutsideClick.bind(this); | |
this.state = { | |
popupVisible: false | |
}; | |
} | |
handleClick() { | |
if (!this.state.popupVisible) { | |
// attach/remove event handler | |
document.addEventListener('click', this.handleOutsideClick, false); | |
} else { | |
document.removeEventListener('click', this.handleOutsideClick, false); | |
} | |
this.setState(prevState => ({ | |
popupVisible: !prevState.popupVisible, | |
})); | |
} | |
handleOutsideClick(e) { | |
// ignore clicks on the component itself | |
if (this.node.contains(e.target)) { | |
return; | |
} | |
this.handleClick(); | |
} | |
render() { | |
return ( | |
<div className="popover-container" ref={node => { this.node = node; }}> | |
<button | |
onClick={this.handleClick} | |
> | |
Toggle Popover | |
</button> | |
{this.state.popupVisible && ( | |
<div | |
className="popover" | |
> | |
{'I\'m a popover!'} | |
</div> | |
)} | |
</div> | |
); | |
} | |
} | |
ReactDOM.render(<Popover />, document.getElementById('App')); |
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, { Component } from 'react'; | |
import PropTypes from 'prop-types'; | |
/** | |
* Component that alerts if you click outside of it | |
*/ | |
export default class OutsideAlerter extends Component { | |
constructor(props) { | |
super(props); | |
this.setWrapperRef = this.setWrapperRef.bind(this); | |
this.handleClickOutside = this.handleClickOutside.bind(this); | |
} | |
componentDidMount() { | |
document.addEventListener('mousedown', this.handleClickOutside); | |
} | |
componentWillUnmount() { | |
document.removeEventListener('mousedown', this.handleClickOutside); | |
} | |
/** | |
* Set the wrapper ref | |
*/ | |
setWrapperRef(node) { | |
this.wrapperRef = node; | |
} | |
/** | |
* Alert if clicked on outside of element | |
*/ | |
handleClickOutside(event) { | |
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) { | |
alert('You clicked outside of me!'); | |
} | |
} | |
render() { | |
return <div ref={this.setWrapperRef}>{this.props.children}</div>; | |
} | |
} | |
OutsideAlerter.propTypes = { | |
children: PropTypes.element.isRequired, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment