My goal is to close the modal when clicking outside the div element
. Take a look at my code below.
// The onClose function is a 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 where I have been working on my code
const handleClickOutside = (e: any) => {
if (e.target.id === 'modal-container') onClose()
}
In the above code snippet, I used e:any
, and everything seemed fine.
However, after removing e:any
and adding
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()
}
The implementation of this useEffect hook and function resulted in errors being thrown.
Specifically, two occurrences of handleClickOutside
are marked as errors, as well as the usage of id
.
Furthermore, VScode gives an tooltip stating No overload matches this call.
for both instances.
If you notice any mistakes or have suggestions, please let me know. Thank you.