Handle click outside of React component | ReactJS Component Detect Click Outside Listener of HTML Element This will be helpful when we need to check click outside event for multiple elements on same component |
The first thing you need to know is that you can attach and detach mousedown listeners on the document object itself. |
This is how we will attach mousedown listener for our component. |
Using this function we will let parent component that some click event triggered out of the element passed to component so parent class can take some action when click outside happened. |
And we will get notified when outside click triggered of an specific element. |
import React, { Component } from "react"; import "./styles.css"; class OutsideClickCheckHandler extends Component { constructor(props) { super(props); this.parent = props.parent; this.tag = props.tag; this.classToCHeck = "outside_click_check_handler_" + ++OutsideClickCheckHandler.counter; this.setWrapperRef = this.setWrapperRef.bind(this); this.handleClickOutside = this.handleClickOutside.bind(this); } componentDidMount() { document.addEventListener("mousedown", this.handleClickOutside); } componentWillUnmount() { document.removeEventListener("mousedown", this.handleClickOutside); } setWrapperRef(node) { this.wrapperRef = node; if (node !== undefined && node !== null) { node.classList.add(this.classToCHeck); } } handleClickOutside(e) { if (!e.target.closest("." + this.classToCHeck)) { this.parent.someOneClickedOutsideMe(this.tag); } } render() { return <div ref={this.setWrapperRef}>{this.props.children}</div>; } } export default OutsideClickCheckHandler; if (OutsideClickCheckHandler.counter === undefined) { OutsideClickCheckHandler.counter = 0; } |
This is how will receive notification when outside click triggered |
This is how we will use component to detect oustide click of an element, you can set multiple child component from a single component with different tag so that you know which element is clicked outside. |
Full example at CodeSandBox.IO |
Saturday, December 26, 2020
Handle click outside of React component | ReactJS Component Detect Click Outside Listener of HTML Element
Subscribe to:
Post Comments (Atom)
Great work.
ReplyDelete