DEV Community

loading...

How to work with SVG on react

Saugat Rai
Been working with frontend stuff and lately more into React
Updated on ・2 min read

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.

Discussion (0)