How do i dynamically create JSX tag in React using typescript?

Viewed 526

I want to import react-icons dynamically.

This works in Javascript, but how do i convert this to Typescript without getting all sorts of errors?

Code:

import * as ReactIcons from 'react-icons/all';
const getIcon = (icon) => {
  const TagName = ReactIcons[icon];
  return <TagName />;
};

Here is output from .d.ts files from react-icons if that helps:

// node_modules/react-icons/all.d.ts
export * from './fa';
export * from './fa';
export * from './io';
export * from './md';
export * from './ti';
export * from './go';
export * from './fi';
export * from './gi';
export * from './gi';
export * from './gi';
1 Answers

You could do it like:

import * as ReactIcons from 'react-icons/all';

type GetIconProps = {
  icon: keyof typeof ReactIcons;
}

const getIcon = ({icon}: GetIconProps) => {
  const TagName = ReactIcons[icon];
  return <TagName />;
};

// Example
getIcon({icon: keyof typeof ReactIcons})

Or even shorter:

const getIcon = ({ icon }: GetIconProps) => {
  const TagName = ReactIcons[icon];
  return <TagName />;
};

Must say it feels a bit hacky though, so would try to import straight from the package instead.

Related