Реактивно реагируйте на иконки и получайте иконки динамически
Как получить иконки динамически в React, используя расширение React Icon kit? Я пытаюсь найти способ динамически добавить значок в MAP-цикле, когда я получаю их из массива "sociallinks"
вот часть кода
....
import { Icon } from 'react-icons-kit'
import {facebook} from 'react-icons-kit/feather/facebook';
import {instagram} from 'react-icons-kit/feather/instagram';
import {twitter} from 'react-icons-kit/feather/twitter';
....
// dynamic array from redux store
"sociallinks": [
{
"_id": 1,
"type": "facebook",
"linkname": "Facebook",
"link": "https://www.facebook.com/zzzzz/"
},
{
"_id": 2,
"type": "instagram",
"linkname": "Instagram",
"link": "https://www.instagram.com/yyy/"
},
{
"_id": 3,
"type": "twitter",
"linkname": "Twitter",
"link": "https://twitter.com/xxx"
},
{
"_id": 4,
"type": "youtube",
"linkname": "Youtube",
"link": "https://www.youtube.com/user/youtube"
}
]
// problem is here how to markup icon = {xxxxx} from map item.type? item.link and item.linkname works fine.. but not item.type :(((
<ul>
{this.props.data.socialLinks.map((item,i) => (
<li key = {i}> <a href = {item.link}><Icon size={18} icon={item.type} />{item.linkname}</a></li>
))
}
</ul>
1 ответ
import { FC } from "react";
import { IconType } from "react-icons/lib";
import * as FaIcons from "react-icons/fa";
import * as MdIcons from "react-icons/md";
import * as HiIcons from "react-icons/hi";
type IconMap = Record<string, IconType>;
type Library = "fa" | "md" | "hi";
interface IDynamicIcon {
lib: Library;
icon: string;
size?: number;
color?: string;
style?: React.CSSProperties | undefined;
}
export const DynamicIcon: FC<IDynamicIcon> = ({
lib,
icon,
size = 16,
color = "#111",
style,
}) => {
const Icon: IconType = (returnLibraryIcons(lib) as IconMap)[icon];
return (
<Icon size={size} color={color} style={style} />
);
};
const returnLibraryIcons = (lib: Library) => {
const LibraryIcons = {
fa: FaIcons,
md: MdIcons,
hi: HiIcons,
};
return LibraryIcons[lib];
};