Next.js Discord

Discord Forum

How to turn a text value into TSX?

Unanswered
VoidPointer posted this in #help-forum
Open in Discord
I'm currently using this, but I strongly suspect there is a better way.
function getIcon(iconName: string) {
    const icon = User;
    switch (iconName.toLowerCase()) {
        case "briefcase": return Briefcase;
        ...
        case "award": return Award;
        default: return icon;
    }
}

This is because I have sections defined in json or a db where I can only store an icon name.

3 Replies

Saint Hubert Jura Hound
I would create a union type for the icon name. Then a record using that type as key. That way your getIcon function could take a IconName type insead and return IconRecord[iconName].
And youd also be able to validate the icon name that u store in the db using that iconname union
Thanks, but after getting some help on the Reactiflux server, I found the Lucide DynamicIcon, which actually has an iconName property whose type is a union of all possible icon names. The heaviest TS type I've ever seen, with some 1900 values, haha. My current solution looks like this:
import { DynamicIcon } from "lucide-react/dynamic";
import type dynamicIconImports from 'lucide-react/dynamicIconImports';
import { toKebabCase } from "@/lib/formatting";
type LucideIconName = keyof typeof dynamicIconImports;
...
<DynamicIcon name={toKebabCase(section.iconName) as LucideIconName} />
Saint Hubert Jura Hound
I see thats cool. As long as it doesnt increase bundle size which i assume it doesnt that looks good :)