Home > Enterprise >  Dynamic import of react-icons
Dynamic import of react-icons

Time:09-02

Is it possible to import dynamically react-icons if each of icon is a separate component? My code looks like this:

import React from 'react';

import { Icon1, Icon2, Icon3, Icon4 } from 'react-icons/ri';

const Foo = () => (
  <div className="xxx">
    <div className="y">
      <Icon1 />
    </div>
    <div className="y">
      <Icon2 />
    </div>
    <div className="y">
      <Icon3 />
    </div>
    <div className="y">
      <Icon4 />
    </div>
  </div>
);

export default Foo;

and would want it to look close to this:

import React from 'react';

const Buttons = () => {
  const iconsList = ['Icon1', 'Icon2', 'Icon3'];
  const renderIcon = (icon) => {
   const Icon = icon;
   return (
    <div className="y">
     <Icon />
    </div>
   )
  }

  return (
   <div className="d-flex align-items-center justify-content-end">
    {iconsList.map(icon => renderIcon(icon))}
   </div>
 )
};

export default Buttons;

The problem I face is how to make the import of icons work there if I didn't want to import all icons using *. Also the problem is that if I make


import { Icon1, Icon2, Icon3, Icon4 } from 'react-icons/ri'

at the top, it still doesn't work for the second version of code.

CodePudding user response:

You have to replace the strings values of your icons in the iconsList array with the Icon component itself.

Just change :

const iconsList = ['Icon1', 'Icon2', 'Icon3'];

to :

const iconsList = [Icon1, Icon2, Icon3];

And add a key to prevent Each child in a list should have a unique "key" prop.Warning like this :

{iconsList.map((icon, index) => renderIcon(icon, index))}

and :

const renderIcon = (icon, index) => {
    const Icon = icon;
    return (
      <div className="y" key={index}>
        <Icon />
      </div>
    );
  };

this is an example in codesandbox

Note : If you import all icons using * , you're importing hundreds of icons at once which is probably not ideal.

  • Related