Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!