React handle click outside
by karlovac
HTML
<div id="app">
</div>
<a href="http://www.example.com" data-method="get" target="_blank" id="outsideAppLink">A link outside the react app</a>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
margin: 20px;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
#outsideAppLink {
background-color: yellow;
}
React
class TodoApp extends React.Component {
constructor(props) {
super(props)
this.wrapperRef = React.createRef();
this.setWrapperRef = this.setWrapperRef.bind(this);
this.handleClickOutside = this.handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener('click', this.handleClickOutside);
}
handleClickOutside(e) {
console.log('handleClickOutside element ID:', e.target.id);
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
console.log('click outside React app');
event.preventDefault();
event.stopPropagation();
}
}
setWrapperRef(node) {
this.wrapperRef = node;
}
render() {
return (
<div ref={this.setWrapperRef}>
<a href="http://www.example.com/" data-method="get" target="_blank" id="insideAppLink">A link in the react app</a>
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))