admin管理员组

文章数量:1315792

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: =/src/Other.tsx:0-172

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

Share Improve this question edited Dec 26, 2022 at 7:04 ghybs 53.4k6 gold badges86 silver badges114 bronze badges asked Dec 26, 2022 at 6:35 Tina GlennTina Glenn 1251 silver badge9 bronze badges 5
  • in App.ts try const myRef = useRef<HTMLDivElement>(); – Layhout Commented Dec 26, 2022 at 6:44
  • I tried this stackoverflow./questions/66963289/… but doesn't work – Tina Glenn Commented Dec 26, 2022 at 6:44
  • @Layhout not working – Tina Glenn Commented Dec 26, 2022 at 6:45
  • i opened your demo, there's no error. – Layhout Commented Dec 26, 2022 at 6:51
  • in App.ts, i imported useEffect and added useEffect(()=>{console.log(myRef.current)},[]). and i get the element. – Layhout Commented Dec 26, 2022 at 6:54
Add a ment  | 

2 Answers 2

Reset to default 8

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

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

本文标签: javascriptUsing forwardRef in other component got type errorStack Overflow