I have successfully created a component that utilizes next/dynamic to import react-icons only when needed. However, I am struggling to properly define the TypeScript types for this component. Despite this issue, the component itself is functioning as expected.
For those interested in viewing the TypeScript code, here is a link to the codesandbox: https://codesandbox.io/s/nextjs-dynamic-import-with-react-icons-zk1kz9
The code :
import dynamic from "next/dynamic";
const DynamicIcon = ({
iconFamily,
icon,
...rest
}: {
iconFamily: keyof typeof Icons;
icon: string;
}) => {
const Icons = {
// Dynamic imports for various icon families
};
const Icon = iconFamily && icon ? Icons[iconFamily] : null;
if (!Icon) return <></>;
return (
<>
<Icon {...rest} />
</>
);
};
export default DynamicIcon;
The error :
./components/DynamicIcon.tsx:12:17
Type error: Argument of type '() => Promise<typeof import("/sandbox/node_modules/react-icons/ci/index") | IconType | undefined>' is not assignable to parameter of type 'DynamicOptions<IconBaseProps> | Loader<IconBaseProps>'.
Type '() => Promise<typeof import("/sandbox/node_modules/react-icons/ci/index") | IconType | undefined>' is not assignable to type '() => LoaderComponent<IconBaseProps>'.
Type 'Promise<typeof import("/sandbox/node_modules/react-icons/ci/index") | IconType | undefined>' is not assignable to type 'LoaderComponent<IconBaseProps>'.
Type 'typeof import("/sandbox/node_modules/react-icons/ci/index") |IconType | undefined' is not assignable to type 'ComponentType<IconBaseProps> | { default: ComponentType<IconBaseProps>; }'.
Type 'undefined' is not assignable to type 'ComponentType<IconBaseProps> | { default: ComponentType<IconBaseProps>; }'.
I have attempted multiple methods of defining the type (such as strings or keyof typeof IconType), but have not yet found a solution.