Home > Blockchain >  Using forwardRef in other component got type error
Using forwardRef in other component got type error

Time:12-26

I got this error:

Type 'ForwardedRef<unknown>' is not assignable to type 'LegacyRef<HTMLDivElement>'

import React from "react";

const Other = React.forwardRef((props, ref) => {
  return (
    <div ref={ref}>
      <h1>Other</h1>
    </div>
  );
});

export default Other;

Is this the right usage?

Demo: https://codesandbox.io/s/summer-shadow-5ul13e?file=/src/Other.tsx:0-172

CodePudding user response:

Simply make sure to provide type arguments to forwardRef, as shown for example here:

import React from "react";

const Other = React.forwardRef<HTMLDivElement, unknown>((props, ref) => {
  return (
    <div ref={ref}>{/* Okay */}
      <h1>Other</h1>
    </div>
  );
});

Playground Link

CodePudding user response:

Initialise useRef with null initially and type <HTMLDivElement>. Also, apply type <HTMLDivElement> to forwardRef as well. Check on mount if ref is assigned correctly.

Here is the Sandbox Link

  • Related