I trying to define icon as JSX.Element type in a config file but I getting an error with TypeScript when using this config to render in component. How I can fix it?
JSX element type ‘Icon’ does not have any construct or call
signatures.ts(2604) ‘Icon’ cannot be used as a JSX component. Its type
‘Element’ is not a valid JSX element type.ts(2786)
user-config.ts
export interface UserConfig {
text: string;
value: string;
icon?: JSX.Element;
}
export const userConfig: UserConfig[] = [
{
text: 'John',
value: 'john-123',
icon: UserIcon,
},
{
text: 'Doe',
value: 'doe-456',
icon: UserIcon,
},
];
index.tsx
<div>
{userConfig.map(({ text, value, icon: Icon }, index) => (
<div key={index} className="flex items-center justify-start flex-col">
{Icon && <Icon />}
<span data-user={value}>{text}</span>
</div>
))}
</div>
>Solution :
It shouldn’t be just JSX.Element. It should be a function that returns a JSX.Element:
type Props = {
Icon?: () => JSX.Element
}
const Component: React.FC<Props> = ({ Icon = null }) => {
return <div>{
Icon && <Icon /> // no error
}</div>
}