Frank
Frank

Reputation: 1

How Can I Render react-icons

How Can I Render react-icons How Can I Render react-icons How Can I Render react-icons How Can I Render react-icons

Upvotes: -1

Views: 653

Answers (2)

Roger Silva Gomes
Roger Silva Gomes

Reputation: 1

You shoud first import the icons that you want to use from library using:

import * as FaIcons from "react-icons/fa";

If you are using TS, declare the IconMap and Library Types:

type IconMap = Record<string, IconType>;
type Library = "fa" | "md" | "hi";

And then, create the interface of your component describing what it should recieve on props, something like this:

interface IDynamicIcon {
  lib: Library;
  icon: string;
  size?: number;
  color?: string;
  style?: React.CSSProperties | undefined;
}

Inside your DynamicIcon component, you shoud add a constant that map the imported lib and return the IconComponent, using returnLibraryIcons function:

const Icon: IconType = (returnLibraryIcons(lib) as IconMap)[icon];

Note that returned Icon is exactly the icon recieved from props (lib and icon).

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,
  style,
}) => {
  const Icon: IconType = (returnLibraryIcons(lib) as IconMap)[icon];

  return (
    <Icon size={size} color={color ?? "#111"} style={style} />
  );
};

const returnLibraryIcons = (lib: Library) => {
  const LibraryIcons = {
    fa: FaIcons,
    md: MdIcons,
    hi: HiIcons,
  };

  return LibraryIcons[lib];
};

Upvotes: 0

Nick
Nick

Reputation: 16586

You should just be able to use the find method and then add the icon of the found item to your JSX:

const icons = [
  { name: 'react', icon: <FaReact /> },
  { name: 'tailwind', icon: <SiTailwindcss /> },
];


function MyComponent() {
  const found = icons.find(({ name }) => name === 'react');

  return <>{found.icon}</>;
}

Upvotes: 1

Related Questions