Search code examples
htmlreactjstypescriptdynamiccomponents

React - convert a string to a component name - problem


Hi I work on some improvments and I came across some issue with changing string with name of my icon component to lower case which generate a error becuasue icons are not showed :/ Everything works before fine because I passed original name of components in the right places. code of function with problem:

function generateIconComponent(IconName: string): JSX.Element {
  return(
    <>
      <div id='iconComponent'>
        <IconName size='56' />
      </div>
    </>
  );
}

At the picture after run of code in marked place should be "Binoculars" instead "binoculars". Also I cant use another additional outer libs to achieve this goal!!!

error

I looked for answer on forum and I found https://www.google.com/url?sa=t&source=web&rct=j&opi=89978449&url=https://stackoverflow.com/questions/29875869/react-jsx-dynamic-component-name&ved=2ahUKEwjl0qW-pKaGAxV_JBAIHdE2DvoQFnoECCMQAQ&usg=AOvVaw2k4vouwBkA8S324WfJfDI9 but it wasn't helpful.


Solution

  • In order to achieve this, you would need a mapping, to map a key to an icon. For example:

    const iconMapping = {
      'Binoculars': Binoculars, // this is the actual icon
    };
    

    and then your generateIconComponent can be changed to:

    function generateIconComponent(IconName: string): JSX.Element {
      // Use the passed string to select the appropriate component from the mapping
      const IconComponent = iconMapping[IconName];
    
      return (
        <div id='iconComponent'>
          <IconComponent />
        </div>
      );
    }