Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

220
Visualizações
React component map based on an array

I dynamically create an element based on passed ID:

const Icon: FC<IconPropsI> = ({iconId, ...rest}) => {
  const iconsMap: IconsMapT = {
    IconUser: IconUser,
    IconTime: IconTime,
    IconVideo: IconVideo
  }

  return createElement(iconsMap[iconId], rest)
}

Value of each map property has corresponding functional component.

I would like to avoid repeating myself. I have created a list of IDs instead. With the following array...

export const IconsIds: IconsIdsT = [ 'IconUser', 'IconTime', 'IconVideo', 'manymore...']

...how can I create the map dynamically inside the Icon component, so I don't have to write 200+ different icon IDs three times?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

In iconsMap you could also use property shorthand to not repeat yourself.

So instead of const iconsMap = { IconUser: IconUser } you should be able to do something like const iconsMap = { IconUser, ...otherIcons }

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#property_definitions

Alternatively, there's a babel plugin that can compose all exports from a certain folder to a single object, and then you can get values from this object.

Check this answer

But please, be aware of potential issues - if you will pass wrong iconId, or if your bundler expects all imports being statically defined(AFAIK - at least react-native and expo expects that) - you might face issues with such an approach, and manual map typing might be more resilient solution.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda