Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a ref using Typescript and styled-components

I'm trying to add a ref to React component like this:

const Dashboard: React.FC = () => {
  const [headerHeight, setHeaderHeight] = useState(0);

  const headerRef = React.createRef<HTMLInputElement>();
  useEffect(() => {
    // @ts-ignore: Object is possibly 'null'
    setHeaderHeight(ref.current.clientHeight)
  });

  return (
    <Root>
      <Header ref={headerRef} />

      <div>other contents</div>             
    </Root>
  );
};

<Header /> is a simple React.FC. TS gives an error saying:

Type '{ ref: RefObject; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'. Property 'ref' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'

How can I overcome this issue?

like image 779
Dmitry Stril Avatar asked Mar 05 '26 19:03

Dmitry Stril


1 Answers

Looks like you're trying to give a ref typed for an input element to another React component. If you are trying to forward the ref to an element inside the Header component, you can use React's forwardRef function.

like image 134
Chris B. Avatar answered Mar 07 '26 11:03

Chris B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!