DEV Community

Cover image for How to use react-icons in React with TypeScript
Tapesh Patel
Tapesh Patel

Posted on • Edited on

How to use react-icons in React with TypeScript

Hello everyone..!

This is for the all learners who wants to try and use react-icons which is also an open source and free icons library package to use.

Lets start implementing it.
First and foremost thing to do is, install the npm package by running npm i react-icons or npm install react-icons.

Secondly, you have to install prop-types using npm i prop-types as TypeScript doesn't like the missing props validation and frankly this is the best practice to follow as well.

Once that is install try to import that into your parent component where you want to use it. To do so, use import statement like import {FaDev} from "react-icons".

Check out react-icons page

Next import Icons Types which is provided by react-icons it self to work with Typescript else you might get an error as soon as you start using it normally like we do in react-JavaScript. Use import {IconType } from "react-icons" to import types.

Now we have done the basic setup its time to create a reusable component for using this, which is more common approach according to me. To do so, start by creating the component you can create anywhere but more common convention is to keep these inside components/utils or components/ui folder depends on how is your folder structure, but feel free to adopt as per your need.

Below is the code which you can copy paste.

import { IconType } from "react-icons";
import PropTypes from "prop-types";
interface IconStar {
icon: IconType;
}
const IconComponent: React.FC<IconStar> = ({ icon: Icon }) => {
return <Icon />;
};
IconComponent.propTypes = {
icon: PropTypes.func.isRequired,
};
export default IconComponent;

Woah...! that's it now you are ready to use it just like a normal react component and all the error's you see would be gone.

<IconComponent icon={FaDev}/>

Thanks for reading this and if you like the content, please do like and share, also suggestions in comment are most welcomed.

Top comments (1)

Collapse
 
beatrice_wambui profile image
Beatrice Wambui Mbugua

this worked well. Thank you