DEV Community

loading...

Dynamically render icons in Gatsby

pinutz23 profile image Jannik Wempe ・1 min read

I can't figure out the best way to dynamically use icons based on a users choice in a headless CMS (in this case Netlify CMS).

I made it work in two ways, but both have downsides:

Option 1: via component name

The user enters name of the icon in the CMS (e.g. "FaClock"; the UX is of course another story here).

The component:

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

export const CustomSvg = ({iconName}) => (
  <Box as={Fa[iconName]} />
);
Enter fullscreen mode Exit fullscreen mode

Downside
This has the huge downside, that all icons are included in the bundle, which leads to performance issues.

Option 2: via SVG image uploaded

The user uploads an svg via file picker.

The component:

export const CustomSvg = ({iconURL}) => (
  <img src={iconURL} />
);
Enter fullscreen mode Exit fullscreen mode

Downside
SVG is included as an img and I can't change color etc.

I'm pretty sure there must be a better way...

Discussion (1)

pic
Editor guide
Collapse
raae profile image
Benedicte Raae • Edited

I found this Stack Overflow that might be helpful. Not tested any myself, but the solution by Nick looks promising.

<svg>
  <use xlinkHref={'/images/logo.svg#Version-2'}>
  </use>
</svg>
Enter fullscreen mode Exit fullscreen mode