Home > Mobile >  What is the appropriate type of event for MouseEvent<HTMLDivElement> in Typescript?
What is the appropriate type of event for MouseEvent<HTMLDivElement> in Typescript?

Time:06-20

What I'm trying to do is to close modal when clicking outside div element. Please check my code first.


// onClose function is setState(false) function.

import { useRef, useEffect } from 'hooks'
import { MouseEvent } from 'react'
import { MovieInfo } from 'types/movie'

interface Props {
  info: MovieInfo
  onClose: () => void
}

const Modal = ({ info, onClose }: Props) => {
  const modalRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside)

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  })

  const handleClickOutside = (e: MouseEvent<HTMLDivElement>) => {
    if (e.target.id === 'modal-container') onClose()
  }

  return (
    <div id='modal-container' ref={modalRef}>
      <div>
        <button type='button' onClick={onClose}>
          close
        </button>
      </div>
    </div>
  )
}

export default Modal

This is my Component, so far, I was writing my code

  const handleClickOutside = (e: any) => {
    if (e.target.id === 'modal-container') onClose()
  }

using any, so there seemed no problem at all.

However, after remove e:any and add e: MouseEvent<HTMLDivElement>,

  useEffect(() => {
    document.addEventListener('mousedown', handleClickOutside)

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  })

  const handleClickOutside = (e: MouseEvent<HTMLDivElement>) => {
    if (e.target.id === 'modal-container') onClose()
  }

This useEffect hook and function make errors.

More precisely, two handleClickOutside are underlined, and id is underlined

and VScode gives an tooltip No overload matches this call. , No overload matches this call. for each.

If I'm missing something, please let me know. Thank you.

CodePudding user response:

import { MouseEvent } from 'react'

This type is for the events that react emits, eg when you use the onClick prop. Since you're subscribing directly to the document, you will be receiving a native dom event, not a react event, and so you need to use the dom event's type. It has the same name as the one from react, but you don't import it.

The fix is to delete the import, and remove the <HTMLDivElement> part (since the dom event isn't a generic). Also, the type information says that e.target might be null, so you'll either need to check for null or assert that it's not null.

const handleClickOutside = (e: MouseEvent) => {
    if (e.target?.id === 'modal-container') onClose()
}
  • Related