How do I make Typescript accept the "useRef" value in React?

Asked

Viewed 58 times

4

export const Test = (): JSX.Element => {
    const wrapperRef = useRef(null);

    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            if (wrapperRef.current && !wrapperRef.current.contains(event.target)) {
                console.log("Fora!");
            } else {
                console.log("Dentro!");
            }
        }

        document.addEventListener("mousedown", handleClickOutside);
        return () => {
            document.removeEventListener("mousedown", handleClickOutside);
        };
    }, [wrapperRef]);

    return (
        <div ref={wrapperRef}>
    )
};

Under "! wrapperRef.current." Typescript shows me this error:

(Property) MutableRefObject<null>.current: null

"Object is possibly 'null'. ts(2531)

inserir a descrição da imagem aqui

How do I fix this?

1 answer

5


Elements of the GIFT

When a reference is created for an element of the DOM, it can:

  1. Reference the DOM element;
  2. Being null - because, for example, the component has been disassembled, so it has nothing to reference.

In the question code, the null is already being done, which is good. What’s the problem, then?

There’s no way the useRef know the type of reference that will store if it is initialized as useRef() or useRef(null). To resolve this, just indicate the expected type:

useRef<Tipo | null>(null); // inicializar com `null` é opcional, mas prefiro deixar explícito

In the case of the question, Tipo is HTMLDivElement.

Non-zero values

If a value is stored instead of a reference to an DOM element, useRef may never have a null reference, for example:

type Tipo = { nome: string };
useRef<Tipo>({ nome: 'Stack Overflow' });

In this case, even when the component is being disassembled, the reference shall not be null.


This "way" that the useRef takes a guy’s name Generics. Here are some references about:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.