DEV Community

Cover image for How I use Google Material Icons in React and Tailwind
Musashi
Musashi

Posted on

How I use Google Material Icons in React and Tailwind

Why do I use Google Material Icons instead of any other icon packages or frameworks such as FontAwesome?

  1. All the icons are free to use
  2. More control over the weight of the icons
  3. Fill property with which I can dynamically fill icons (when the button is pressed or menu is selected).

For those of you that use React and Tailwind, the following setup should be enough to easily import and use icons anywhere in the project.

Here is an example:

Using Google Icons in your project

How to use:

Import the icon style you want into your globals.css or index.css file. In my case, I have imported the Rounded Icon versions

@import url("https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200");
Enter fullscreen mode Exit fullscreen mode

Create a new file, preferably in your components or ui folder. I have called the file icon-wrapper.tsx since I am working with typescript in my project. In the file paste the following code:

export default function Icon({ icon, size = '24px', fill=0}: {icon: string; size?: string; fill?: number;}) {
    return (     
        <span className={`flex items-center ${spin? 'animate-spin' : ''} material-symbols-rounded`} 
            style={{ fontSize: size, fontVariationSettings: `'FILL' ${fill}, 'wght' 400, 'GRAD' 0, 'opsz' 24`} }>
            {icon}
        </span>
    )
}
Enter fullscreen mode Exit fullscreen mode

Note that the material-symbols-rounded in the className should be the same class you have imported in the css file.

Now you can use the Icons anywhere in the project as shown below:

<Icon icon="chevron_left"/>
Enter fullscreen mode Exit fullscreen mode

Note: the icon="" field should contain the name of the icon as given in the website.

Customize the icon properties:

{/*Variable sizes*/}
<Icon icon="warning" size="12px"/>
{/*Give fill to the icons based on user action*/}
<Icon icon="grid_view" fill={tab === "dashboard" ? 1 : 0}/>
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
matr1x profile image
Matr1X

Helpful

Collapse
 
iamriteshkoushik profile image
Ritesh Koushik

Heavy blogger