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

mrpaulishaili

Paul C. Ishaili

Posted on June 30, 2024

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.

💖 💪 🙅 🚩
mrpaulishaili
Paul C. Ishaili

Posted on June 30, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related