Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if the user clicked inside the current component?

Tags:

reactjs

I have a component called Dialog, in which I attach an event listener on mouse clicks on the window object.

componentDidMount() {
    document.addEventListener('click', this.handleClick);
}

componentWillUnmount() {
    document.removeEventListener('click', this.handleClick);
}

How can I detect (in the handleClick function) whether a click has been fired inside the component or outside? Note that this dialog contains different elements and child components.

like image 804
Matthew Avatar asked Nov 09 '16 13:11

Matthew


People also ask

How will you detect click inside component in React?

To determine whether the click position is inside or outside our component, combine window. onclick with the useEffect() hook as follows: useEffect(() => { window. onclick = (event) => { if (event.

How do you check if an element has been clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.

How do you detect a click outside the React component?

Detecting an outside click of a functional component Let's build an HTML tooltip by creating a React functional component named InfoBox . The tooltip will appear when the user clicks a button, and it will be closed if the user clicks outside of the tooltip component.


1 Answers

parent.contains(child) is your friend. This solution using refs might not be perfect, but simply using this does not work as it's not a proper DOM node. I'm using React 15 here, so keep in mind that in earlier versions you'd have to use .getDOMNode() on the parent.

class Dialog extends React.Component {
  constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
  }
  componentDidMount() {
    document.addEventListener('click', this.handleClick);
  }
  componentWillUnmount() {
    document.removeEventListener('click', this.handleClick);
  }
  handleClick(e) {
    if (this.node.contains(e.target)) {
      console.log('You clicked INSIDE the component.')
    } else {
      console.log('You clicked OUTSIDE the component.')
    }
  }
  render() {
    return(
      <span ref={node => this.node = node}>
        Level 0<br/>
        <span>
          Level 1.<br/>
          <span>Level 2.</span>
        </span>
      </span>
    );
  }
}

ReactDOM.render(<Dialog/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="View"></div>
like image 180
Fabian Schultz Avatar answered Oct 18 '22 14:10

Fabian Schultz