user16754275
user16754275

Reputation:

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?

Upvotes: 0

Views: 47

Answers (1)

Klymenko Kyrylo
Klymenko Kyrylo

Reputation: 661

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.

Upvotes: 1

Related Questions