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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With