Search code examples
javascriptreactjstypescriptref

ref not available in HTMLAttributes<HTMLDivElement>


I have a reusable wrapper component which like this:

import { FC, HTMLAttributes } from "react";

const Wrapper: FC<HTMLAttributes<HTMLDivElement>> = ({
  children,
  className,
  ...props
}) => (
  <div className={`h-[90vh] ${className ? className : ""}`} {...props}>
    {children}
  </div>
);

export default Wrapper;

But I can't add the ref prop to the component.

<Wrapper ref={ref} ...

Property 'ref' does not exist on type 'IntrinsicAttributes & HTMLAttributes<HTMLInputElement>'.

What typescript type should I use for the Wrapper component and add the ref prop without an error?


Solution

  • If you would like to use FC type, then you'll need to use ComponentPropsWithRef<"div"> type for props. (don't forget to wrap component in forwardRef or ref won't work)

    Alternatively, you can omit FC type and just define component like this:

    import React, { forwardRef, ComponentPropsWithoutRef } from "react";
    
    const Wrapper = forwardRef<HTMLDivElement, ComponentPropsWithoutRef<"div">>(({
      children,
      className,
      ...props
    }, ref) => (
      <div ref={ref} className={`h-[90vh] ${className ? className : ""}`} {...props}>
        {children}
      </div>
    ));
    

    This way you will be able to pass ref to the component and it will be typechecked.