Home > other >  react dynamic component type example
react dynamic component type example

Time:05-02

How/Where can i add types to the dynamic component Icons[name] ?

import * as Icons from "react-icons/fa";

const DynamicFaIcon = ({ name }: any) => {
  const IconComponent = Icons[name];

  return <IconComponent />;
};

enter image description here

CodePudding user response:

You could just grap the keys from the import, since its a JS object like any other:

import * as Icons from "react-icons/fa";

const DynamicFaIcon = ({ name }: {name: keyof typeof Icons}) => {
  const IconComponent = Icons[name];

  return <IconComponent />;
};

I would be careful about importing literally everything from that package though. There's over 1,500 components in there, does any application actually make use of all of them? You'll end up bundling way more than you need.

CodePudding user response:

This is my answer on dynamic icons problem, is it your question answer ?? , maybe it will help you, use it like this `

import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {library} from '@fortawesome/fontawesome-svg-core';
import * as Icons from '@fortawesome/free-solid-svg-icons';

const iconList = Object.keys(Icons)
    .filter((key) => key !== 'fas' && key !== 'prefix')
    .map((icon) => Icons[icon]);

library.add(...iconList);

const Feature = ({ carFeature }) => {
    console.log(carFeature);
    return (
        <div>
            <FontAwesomeIcon icon={carFeature?.icon} color="#ddd" />
            <h3>{carFeature?.name}</h3>
            <p>{carFeature?.desc}</p>
        </div>
    );
};
export default Feature;

If no then try this

Not the OP's direct issue but for users encountering this error for libraries not under their control, one can suppress this error is by adding:

{
  ...
  "suppressImplicitAnyIndexErrors": true,
  ...
}

to the tsconfig.json file.

Read more here Question Answer

  • Related