Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using forwardRef in other component got type error

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

like image 871
Tina Glenn Avatar asked Oct 19 '25 08:10

Tina Glenn


1 Answers

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

like image 106
ghybs Avatar answered Oct 21 '25 00:10

ghybs