DEV Community

Saugat Rai
Saugat Rai

Posted on • Updated on

 

How to work with SVG on react

SVGs are great. They are great to use for icons since they don't blur out when zoomed. We can change the fill color while adding hover effect and so much more.

In this tutorial, we will be making a component that will render SVG icons and will also take color options so that we can the color.

ICONS

First lets start off with a constant ICONS variables that will hold all the values of SVG like viewbox and path. Viewbox is necessary to define position and dimension.

Wrapper

In order to render SVG, we need wrapper. So we will make a wrapper file.

This component will receive props like width, height, color and icon name. The width, height and icon name will be used in svg tag and the color will be used in path tag. Icon name can be anything as long as it is included in ICONS constant.

This will help to get the value of viewbox from the icon name provided.

And this will help to fill the color to SVG. If the color is not provided then the default color will be used.

You can also define propType if you want to.

Implementation

This tutorial was possible with the help of this medium article that I came across while searching.

https://medium.com/@david.gilbertson/icons-as-react-components-de3e33cb8792

Well, that's all for now. Will return soon with another tutorial.

Oldest comments (0)

Top Posts from the React Ecosystem

1. Changes In The Official React Documentation

The former React Docs Beta has been officially released as the updated React documentation at react.dev after years of hard work and refinement. Check out the brand new React Docs: What’s New in the Updated React Docs

2. CRA's Time is Over

React developer team has removed create-react-app (CRA) from official documentation rendering it no longer the default setup method for new projects. The bulky setup, slow, and outdated nature of CRA led to its removal: create-react-app is officially dead

3. How to Fetch Dev.to Articles for Your Portfolio

Integrate the articles of your Dev.to profile into your personal portfolio with either React, Vue, or Next.js by following these simple steps. It outlines how to include frontend to pull the information and correctly utilizes the Dev.to API: How to Fetch Your Dev.to Articles for Your Portfolio with React