'React Typescript: Type issue when passing multiple refs to child component
I have a main component that passes down multiple refs to Panels
component like so
import { useRef } from 'react';
import Panels from './Panels';
export const Main = (props) => {
const childRefs = useRef<HTMLDivElement[]>([]);
const sliderRef = useRef<HTMLDivElement>(null);
const wrapperRef = useRef<HTMLDivElement>(null);
const carouselRefs = useRef({ childRefs, sliderRef, wrapperRef });
return (
<div>
<Panels
ref={carouselRefs}
children={props.chldren}
currentPanel={props.currentPanel}
/>
</div>
);
};
export default Main;
and inside of the Panels
component I have this code:
import React, { FC, ForwardedRef, MutableRefObject, RefObject } from 'react';
export interface IPanels {
children: React.ReactNode[];
currentPanel: number;
ref: MutableRefObject<{
childRefs: MutableRefObject<HTMLDivElement[]>;
sliderRef: RefObject<HTMLDivElement>;
wrapperRef: RefObject<HTMLDivElement>;
}>;
}
export const Panels: FC<IPanels> = React.forwardRef(
(
{ children, currentPanel }: IPanels,
forwardedRef: ForwardedRef<HTMLDivElement>
) => {
const { wrapperRef, childRefs, sliderRef } = forwardedRef.current;
return (
<div ref={wrapperRef}>
<div ref={sliderRef}>
{children &&
children.length &&
children.map((child, index) => {
return (
<div
className="mx-4 mb-12"
ref={(element) => {
return element && childRefs.current.push(element);
}}
key={index}
>
{child}
</div>
);
})}
</div>
</div>
);
}
);
export default Panels;
I can see there is a typescript error over export const Panels
that reads:
Type 'ForwardRefExoticComponent<Pick<IPanels, "children" | "currentPanel"> & RefAttributes<HTMLDivElement>>' is not assignable to type 'FC<IPanels>'.
I think I might have the ref
type in IPanels
incorrectly, although I'm not entirely sure how. Any help would be great, thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|