Home > Software design >  How to import icon / jsx element by string?
How to import icon / jsx element by string?

Time:09-26

I'm working on an icon selector at the moment. Once an icon is chosen, the selector returns the icon as a string, like "AirBalloon". Then, I want to display that icon on my page, so I need to import it (I'm using https://www.npmjs.com/package/tabler-icons-react). Normally, i would do it like import {AirBallon} from 'tabler-icons-react';. So I tried this:

<IconSelector
    active={iconSelectorActive}
    setIcon={setIcon}
    additionalEvent={async () => {
        console.log(icon); // Logs the icon I selected
        setActiveIcon((await import('../../node_modules/tabler-icons-react/dist/icons/'   icon)));
        }}
></IconSelector>

But if I try to embed it into my jsx like that:

<Button
    onClick={() =>
        setIconSelectorActive(!iconSelectorActive)
    }
    variant="PRIMARY"
>
    {activeIcon}
</Button>

It throws the error Error: Cannot find module './' when I click an item from the selector.

How do I fix this? Greetings, PixelPage

CodePudding user response:

First, you need to import all the icons from the library like this:

import * as allIcons from "tabler-icons-react";

And then retrieve the selected icon by using its name like this:

const iconNameToBeUsed = "Activity";
const IconToBeUsed = allIcons[iconNameToBeUsed];

Finally render the selected icon jsx like this:

<IconToBeUsed />

You can take a look at this sandbox for a live working example of this solution.

  • Related