Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use useImperativeHandle in function component with typescript,it will tips some error;

Type '{ focus(): void; }' is missing the following properties from type 'HTMLDivElement': align, addEventListener, removeEventListener, accessKey, and 234 more.ts(2740) index.d.ts(1041, 79): The expected type comes from the return type of this signature.

here is component code :

import React, { forwardRef, useImperativeHandle, useRef } from "react";

type Ref = HTMLDivElement | null;
type SwiperProps = {
  children?: React.ReactNode | null;
  selectedIndex?: number;
};

const Swiper = forwardRef<Ref, SwiperProps>(
  ({ children = null }: SwiperProps, ref) => {
    const inputRef = useRef(null);
    useImperativeHandle(ref, () => ({
      focus() {
        inputRef.current.focus();
      }
    }));
    return (
      <div ref={ref}>
        {children}
        <input type="text" ref={inputRef} />
      </div>
    );
  }
);

export default Swiper;

the full code is in codesandbox;

https://codesandbox.io/s/useimperativehandlecomponenterror-lowon

like image 254
water Avatar asked Jul 13 '26 00:07

water


1 Answers

You have mixed up the type definitions of your refs:

import React, { forwardRef, useImperativeHandle, useRef } from "react";

type Ref = {
  focus: () => void
} | null;
type SwiperProps = {
  children?: React.ReactNode | null;
  selectedIndex?: number;
};

const Swiper = forwardRef<Ref, SwiperProps>(
  ({ children = null }: SwiperProps, ref) => {
    const inputRef = useRef<HTMLInputElement>(null);
    useImperativeHandle(ref, () => ({
      focus() {
        inputRef.current?.focus();
      }
    }));
    return (
      <div>
        {children}
        <input type="text" ref={inputRef} />
      </div>
    );
  }
);

export default Swiper;

The type you expose should describe your imperative handle.

Edit useImperativeHandleComponentError (forked)

like image 163
thedude Avatar answered Jul 14 '26 13:07

thedude



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!