0

I want to import icons from react-icons as defined by an array of strings corresponding to named exports of icon components from react-icons. I cover the cases for each library of icons from react-icons. This is an example of a case for FontAwesome.

lazy(() => import('react-icons/fa').then(module => ({ default: module.Components[icon]})))

The above code snippet was found here as a method of dynamically importing named exports.

I expect this to return a component corresponding to the icon specified by icon, for example let icon = 'FaPhp'; What's happening is an error which says: TypeError: Cannot read property 'FaPhp' of undefined

Casey
  • 444
  • 1
  • 7
  • 22
  • FWIW your error means that `module.Components` is undefined. I suggest adding `console.log(JSON.stringify(Object.keys(module)))` to your `then` lambda to see what is actually in the module object. – Brandon Jan 15 '20 at 23:04
  • It's probably supposed to be `module.exports` not `module.Components` – sjagr Jan 15 '20 at 23:08
  • @sjagr I am using Components otherwise I just have a string which is the name of the desired named export. – Casey Jan 16 '20 at 01:17
  • @Brandon thank you I will try that. I may need to just import Components from 'react'. – Casey Jan 16 '20 at 01:23
  • @Brandon I got something unexpected. Console found ["loaded","id","exports","webpackPolyfill"] – Casey Jan 16 '20 at 02:55
  • Okay, so if I use `module.FaPhp`, the icons render. So now, I'm just figuring out how to use the strings I have of the component names, hence why I was using `Components[icon]`. – Casey Jan 16 '20 at 03:29
  • 1
    `module[icon]` is what you want then. – Brandon Jan 16 '20 at 18:27
  • @Brandon close, I got it figured out last night (see answer) I had to use Icon instead of icon. – Casey Jan 16 '20 at 20:37

1 Answers1

0

React expects all components to be named with a leading capital letter. Therefor, I renamed the iterator icon to Icon, then I omitted the module.Components[icon]and replaced it with module[Icon] which solved my issue!

I figured this out from this post and decided to use the array access notation after realizing I was accessing the library of elements through module.

Casey
  • 444
  • 1
  • 7
  • 22