hat goblin
hat goblin

Reputation: 113

How to detect click outside of class component?

My task is to detect the click outside of component. I've been trying to implement the below code with typescript, but cant find what type should i give to handleClickOutside event so that event.target doesn't throw an error: Argument of type 'EventTarget | null' is not assignable to parameter of type 'Node | null'. No hooks are allowed. Please help.

import React, { Component } from "react";

export default class OutsideAlerter extends Component {
  private wrapperRef: React.RefObject<HTMLInputElement>;
  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);
  }

  handleClickOutside(event) { //problem is here
    if (this.wrapperRef && !this.wrapperRef.current.contains(event.target)) { //and here
      alert("You clicked outside of me!");
    }
  }

  render() {
    return <div ref={this.wrapperRef}>{this.props.children}</div>;
  }
}

Upvotes: 0

Views: 683

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92274

You have to assign a type to your event, note that since you are registering the handler on the document, you need to specify that.

handleClickOutside(event: React.MouseEvent<Document>) {

See https://www.carlrippon.com/React-event-handlers-with-typescript/

Upvotes: 1

Related Questions