Search code examples
reactjslazy-loadingdynamic-importreact-icons

Module is undefined for dynamic import of a named export from an external package


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


Solution

  • 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.