I have a custom React Hook that watches for a click outside of a specific element. It works just fine, but I am having trouble making TypeScript happy in a few places.
App.js
import { useRef, useCallback } from "react";
import useClick from "./useClick";
export default function App() {
const asideRef = useRef(null);
const handleStuff = useCallback(() => {
console.log("a click outside of the sidebar occurred.");
}, []);
useClick(asideRef, handleStuff);
return (
<div className="App">
<aside ref={asideRef}>
<nav>
<ul></ul>
</nav>
</aside>
</div>
);
}
useClick.js
import React, { useEffect } from "react";
const useClick = (ref: React.MutableRefObject<HTMLElement>, cb: () => void) => {
useEffect(() => {
const checkClick = (e: React.MouseEvent): void => {
if (ref.current && !ref.current.contains(e.target as Node)) {
cb();
}
};
document.addEventListener("click", checkClick);
return () => {
document.removeEventListener("click", checkClick);
};
}, [ref, cb]);
};
export default useClick;
The first problem area is in App.js, where the useClick hook is called. TypeScript complains about the first parameter passed to useClick and gives a message of:
Argument of type 'MutableRefObject<null>' is not assignable to parameter of type 'MutableRefObject<HTMLElement>'.
Type 'null' is not assignable to type 'HTMLElement'.ts(2345)
I know this has something to do with me setting the initial value of the ref to null, and the argument for the ref in useClick being annotated as React.MutableRefObject<HTMLElement>. I just don't know how to fix it.
The second problem area is in useClick.js, where the event listeners are added and removed. TypeScript seems to have a problem with my checkClick function. The error is so long that I have no choice but to show a photo of it below.
If anyone has any idea's on how to fix these two issues, so TypeScript will be happy, the help would be greatly appreciated.
