Home > database >  What should I put instead of `null` for useRef?
What should I put instead of `null` for useRef?

Time:12-15

I have a sidebar function to close on a click outside, however I am getting a TypeError: Property 'contains' does not exist on type 'never'.

const sidebar = useRef(null);
  const trigger = useRef(null);

  // Close on click outside
  useEffect(() => {
    const clickHandler = ({ target }: { target: ReactNode }) => {
      if (!sidebar.current || !trigger.current) return;
      if (
        !sidebarOpen ||
        sidebar.current.contains(target) || // Error: Property 'contains' does not exist on type 'never'.
        trigger.current.contains(target)
      )
        return;
      setSidebarOpen(false);
    };
    document.addEventListener('click', clickHandler);
    return () => document.removeEventListener('click', clickHandler);
  });

CodePudding user response:

You can use a generic argument with useRef e.g.

const sidebar = useRef<HTMLElement | null>(null);

And now you will be able to use optional chaining e.g. sidebar.current?.contains

CodePudding user response:

I guess you aren't using typescript. If you were, it would have been easier with a simple not null assertion. Like these:

As you don't have that, you should try something like this:

if(a){//check if `a` is undefined or not, if not then
   console.log(a.b)
   if(a.b){//check if the property in `b` in `a` is defined or not, if defined then
      console.log(a.b.c)
   }
}

It might be confusing at first that, we are checking for a is undefined or not and using a.b? Yes, we are. Even if a si defined and b in a is not. We may not need to worry. As for the worst case, that will give us undefined. But attribute inside undefined, is an error.

  • Related