Last active
November 21, 2023 06:30
-
-
Save akbarjondev/315c7125a7bb8f05c088f3ba769d9949 to your computer and use it in GitHub Desktop.
Listen clicks outside of the component In React.js class component
This file contains hidden or 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"; | |
/** | |
* 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