The example code in mappings.ts
.
import NotificationsIcon from './NotificationsIcon';
import AddIcon from './AddIcon';
import AirplayLineIcon from './AirplayLineIcon';
export const mappings = {
'notifications': NotificationsIcon,
'add': AddIcon,
'airplay-line': AirplayLineIcon
} as const;
export const names = [
"notifications",
"add",
"airplay-line",
} as const
export type IconName = typeof names[number];
This is how the icon component looks.
notifications: (iconProps: SVGProps<SVGSVGElement>) => JSX.Element;
I am facing issues when I try to render the component.
import React from 'react';
import {IconName, mappings} from './mappings';
export const SvgIcon: React.FC<{iconName: IconName, iconSize: number, color:string}> = ({iconName, iconSize, color}) => {
return (
<>
{mappings[iconName]({width: iconSize, height: iconSize, fill: color})}
</>
);
};
the error TypeError: _mappings__WEBPACK_IMPORTED_MODULE_1__.a[iconName] is not a function
Not sure what i am doing wrong here. Please help.
CodePudding user response:
Can you try to invoke the Icon with JSX like this:
const Icon = mappings[iconName]
return <Icon width={iconSize} height={iconSize} fill={color} />
or you could use a helper function provided by react:
return React.cloneElement(mappings[iconName], {width: iconSize, height: iconSize, fill: color})
By the way, I think you can omit the names
constant inside mappings.ts. You can just do the following instead:
export const mappings = {
'notifications': NotificationsIcon,
'add': AddIcon,
'airplay-line': AirplayLineIcon
} as const;
export type IconNames = keyof typeof mappings;
I hope I was able to help, cheers!