Home > database >  Get JSX Element from a Typescript Object
Get JSX Element from a Typescript Object

Time:10-13

My typescript object state.ts is like below

import { IconCalendarEvent, TablerIcon, IconRun } from "@tabler/icons";

export const StateIcon  = {    
  Validated: IconCalendarEvent,
  Running: IconRun
};

Basically this infers to

const StateIcon: {
    Validated: TablerIcon;
    Running: TablerIcon;
}

Now in my React Component , I want to return JSX Element based on a state

So I have written a function

const getIcon = (state: string) => {
  const r = (_.keys(StateIcon) as (keyof typeof StateIcon)[]).find((k) => {
    return k === state;
  });

  return <StateIcon[r] /> 
  
};

But this doesn't work saying JSX element type 'StateIcon' does not have any construct or call signatures

If I try below hard-coded it works fine.

return <StateIcon.Running /> 

I tried changing signature to

const getIcon = (state: string) => {
  const Icon = StateIcon[state];
  return <Icon />;
};

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ Validated: TablerIcon; Running: TablerIcon; }'. No index signature with a parameter of type 'string' was found on type '{ Validated: TablerIcon; Running: TablerIcon; }'

What I am missing here

CodePudding user response:

You can have a "dynamic" component:

const getIcon = (state: string) => {
  const r = (_.keys(StateIcon) as (keyof typeof StateIcon)[]).find((k) => {
    return k === state;
  });

  // Store the chosen component in a variable starting with Uppercase
  const DynamicIcon = StateIcon[r];

  return <DynamicIcon /> 
};
  • Related