Search code examples
reactjstypescriptreact-typescript

How do I safeguard usage of React components that might not exist?


In my project I will possibly get icons/svgs as react components in a folder generated by the backend. There will also be a WAMP (bonefish/autobahn) solution where I get the name of an icon to use (I know this is a bit weird but just let it be that way).

They will place all icons in a folder on an embedded unit, and I will have to get the icons from there. The icons will be exported in a index file and imported where I need them.

structure will be something like this:

.
├─ src
├─── buttonManagement.tsx
|
├─ incons
├─── index.ts
├─── iconA.tsx
├─── iconB.tsx
|
.
.

index.ts

export * from "iconA";
export * from "iconB";

in buttonManagement i then can import all icons and use them like this. I can not use the notation icons.iconName since this is done in runtime and I cant import things I do not know the name of.

import * as icons from "../icons"

const icon = icons["iconA"];

So far so good, but what do I do when backend sends an icon name that does not exist?

const icon = icons["iconC"];

then I get this error

Property 'iconC' does not exist on type 'typeof import("/home/ubuntu/workspace/code/myProject/icons/index")'

How do I do this?

I tried using try/catch

this does not work either

const iconC = icons["iconC"] as React.ComponentType | undefined;

Solution

  • As I understand you are trying to access an icon that does not exist when compile. You can define the type of Icons like below and casting type to icons and return it if the iconC is valid then you complete fine when compiling.

    import * as icons from "../icons"
    
    type Icons = {[key:string]:React.ComponentType} 
    
    const IconC= (icons as Icons)['IconC']
    
    return <>{IconC && <IconC />}</>