DEV Community

Paul C. Ishaili
Paul C. Ishaili

Posted on

How I created reusable React Icon Component using react-icons library in an AstroJs Project.

In the past weeks lately, I have been focused on building clean landing page websites using AstroJs framework.

One of the difficulties I often face however is the limitation of the icon libraries available in the astro-icons, as compared to the react-icon library.

So here's what I decided to do:

import React from 'react';
import * as FaIcons from 'react-icons/fa';
import * as MdIcons from 'react-icons/md';
import * as AiIcons from 'react-icons/ai';
import * as GiIcons from 'react-icons/gi';
import * as IoIcons from 'react-icons/io';
import * as CiIcons from "react-icons/ci";
import * as FiIcons from "react-icons/fi";
import * as LuIcons from "react-icons/lu";

const iconSets = {
  fa: FaIcons,
  md: MdIcons,
  ai: AiIcons,
  gi: GiIcons,
  io: IoIcons,
  ci: CiIcons,
  fi: FiIcons,
  lu: LuIcons,
};

const Icon = ({ name, set = 'fa', size = 24, color = 'currentColor', className = '' }) => {
  const IconComponent = iconSets[set][name];

  if (!IconComponent) {
    console.warn(`Icon ${name} from set ${set} not found`);
    return null;
  }

  return <IconComponent size={size} color={color} className={className} />;
};

export default Icon;
Enter fullscreen mode Exit fullscreen mode

After which I imported this IconX (which I called it, that it doesn't conflict with the icon component from astro-icons) component into the components I would like to use it in.


<IconX size={24} set="ci" name={"CiSearch"} client:load />

Enter fullscreen mode Exit fullscreen mode

Now I have access to the thousand of icons provided by react-icons right in my AstroJs Project.

Do like, share and follow for more.

Enjoy the read.

Top comments (2)

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

I did something very similar to this in my last major project. I'm now using Iconify which I find to be exceptional - the challenge with the approach you are using here is that it includes all of the icons in your project, Iconify avoids this. You can also use the all-files icons version of React Icons, while this takes a long time to install but it will let you pick and choose specific ones and not include everything.

Collapse
 
raajaryan profile image
Deepak Kumar

Hello everyone,

I hope you're all doing well. I recently launched an open-source project called the Ultimate JavaScript Project, and I'd love your support. Please check it out and give it a star on GitHub: Ultimate JavaScript Project. Your support would mean a lot to me and greatly help in the project's growth.

Thank you!