Skip to content

Instantly share code, notes, and snippets.

@akbarjondev
Last active November 21, 2023 06:30
Show Gist options
  • Save akbarjondev/315c7125a7bb8f05c088f3ba769d9949 to your computer and use it in GitHub Desktop.
Save akbarjondev/315c7125a7bb8f05c088f3ba769d9949 to your computer and use it in GitHub Desktop.
Listen clicks outside of the component In React.js class component
import React, { Component } from "react";
/**
* Component o'zidan tashqari bosilsa log chiqaradi
*/
export default class OutsideAlerter extends Component {
constructor(props) {
super(props);
this.wrapperRef = React.createRef();
this.handleClickOutside = this.handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
/**
* Componentdan tashqari bosilsa log xabar beradi
*/
handleClickOutside(event) {
if (this.wrapperRef && !this.wrapperRef.current.contains(event.target)) {
console.log("Mendan tashqarini bosdingiz!");
}
}
render() {
return <div ref={this.wrapperRef}>{this.props.children}</div>;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment