Home > Back-end >  What is the type of a React ref?
What is the type of a React ref?

Time:10-31

I am trying to use a type for my ref but it throws an error

Property 'current' does not exist on type 'HTMLElement.

import { useState, useLayoutEffect } from 'react';

export const useIsOverflow = (ref: HTMLElement) => {
  const [isOverflow, setIsOverflow] = useState(undefined);

  useLayoutEffect(() => {
    const { current } = ref;

    const trigger = () => {
      const hasOverflow = current.scrollHeight > current.clientHeight;

      setIsOverflow(hasOverflow);
    };

    if (current) {
      trigger();
    }
  }, [ref]);

  return isOverflow;
};

What is the type of ref supposed to be here?

CodePudding user response:

That would be MutableRefObject<T>:

import { useState, useLayoutEffect, MutableRefObject } from 'react';

export const useIsOverflow = (ref: MutableRefObject<HTMLElement>) => {
  • Related