I am working on a React JS project. I am using hooks and functional components. I am using ref. I am using useRef because I am in a functional component. But the contains function is not working on ref. Following is my code.
const App = () => {
let refDialog = useRef(null);
document.addEventListener('click', (e) => {
if (refDialog && refDialog.contains(e.target)) {
// I will do something here
}
})
return (
<div>
<Dialog ref={ ref => refDialog = ref}>My dialog content</Dialog>
</div>
)
}
As you can see in my component, in the event listener, it is throwing the following error.
Uncaught TypeError: refDialog.contains is not a function
What is wrong with my code?
Firstly remove typo -
useRf->useRef. Secondly -refDialogis a read-only variable, you can't overwrite it -ref={refDialog}is enough (without ref function). Finally -refDialogwill hold an object withcurrentfield. So the final condition will be: