Home > database >  How to dynamically use icon in a React app based on a string value
How to dynamically use icon in a React app based on a string value

Time:07-06

I have the following setup, and it is working.

import * as Icon1 from 'images/img1.svg'
import * as Icon2 from 'images/img2.svg'

const Foo = () => {
    return (<>
        <AComponent icon={Icon1}/>
    </>)
}

Now the task is to have the icon dynamically determined from a string value, so I try:

import * as Icon1 from 'images/img1.svg'
import * as Icon2 from 'images/img2.svg'

const Foo = () => {

    const theIcon = 'Icon1' // can be 'Icon2' at other times

    return (<>
        <AComponent icon={eval(theIcon)}/>
    </>)
}

This gives Runtime Error: ReferenceError: Icon1 is not defined.

So it would look like React has correctly identify Icon1 as a variable name, but it has failed to locate it from the imports.

Also it is possible to have theIcon = 'img1.svg', if need be. Just really would like to achieve the goal of dynamically assigning this icon.

CodePudding user response:

It's simple:

<AComponent icon={stringVariable === "icon1" ? Icon1 : Icon2}/>

CodePudding user response:

as @messerbill suggests, you can write a method for it which returns the correct value based on the given parameter. The method can contain either a 'switch case' or 'if else statements'. Also you can write an object with values based on icons you have imported:

import * as Icon1 from 'images/img1.svg';
import * as Icon2 from 'images/img2.svg';

const availableIcons = {
 icon1: Icon1,
 icon2: Icon2,
};

const getCorrectIcon:(givenName) => {
    return availableIcons[givenName];
}

const Foo = ({ iconName }) => {

   const theIcon = getCorrectIcon(iconName) ?? defaultValue;

   return (<>
       <AComponent icon={eval(theIcon)}/>
   </>)
}
  • Related