Sass
Different ways to use svg's in your ReactJs app.
May 05, 2020
1 min

We meet many circumstances where we need to import images into our Web page. The usual syntax of importing an image to a Reactjs file is as follows.

import React from 'react
import clockIcon from 'images/clock-icon.png'

export function test() {
  return (
      <img src={clockIcon} alt="Clock icon" />
  )
}

But if you want to use an image as an icon - and change it’s color depending on external factors such as a user hovering on a button, this approach fails. You can’t change the color of an icon when an <img> tag is used.

The following figure shows a button with a grey icon which changes its color to white on button hover.

Changes icon color on hover

There are two easy ways to achieve this.

1. Use css mask-image property

In this method you use a div,

<div className="clockIcon" />

and set these css properties to get the desired result.

.clockIcon{
    width: 50px;
    height: 50px;
    mask-image: url(images/clockIcon.svg)
    mask-size: 100%;
    mask-repeat: no-repeat;
    background-color: grey;
    &:hover{
        background-color: white;
    }
}

Result: A grey color clock-icon which changes to white on hover.

2. Save svg data in a javascript file

In this method, we copy <svg> data and paste it in the return function of a js/jsx/tsx file. In other words, we treat it like an ordinary javascript/typescript file.

import React from 'react';

export function ClockIcon() {
  return (
    <svg className="mySVGClassName" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg">
      <path d="m256 0c-141.164062 0-256 114.835938-256 256s114.835938 256 256 256 256-114.835938 256-256-114.835938-256-256-256zm121.75 388.414062c-4.160156 4.160157-9.621094 6.253907-15.082031 6.253907-5.460938 0-10.925781-2.09375-15.082031-6.253907l-106.667969-106.664062c-4.011719-3.988281-6.25-9.410156-6.25-15.082031v-138.667969c0-11.796875 9.554687-21.332031 21.332031-21.332031s21.332031 9.535156 21.332031 21.332031v129.835938l100.417969 100.414062c8.339844 8.34375 8.339844 21.824219 0 30.164062zm0 0" />
    </svg>
  );
}


Then import and use it wherever required.

import { ClockIcon } from clockIcon.js;
.
.
.
<div>
    <ClockIcon/>
</div>

Do not forget to style it

.mySVGClassName{
    width: 50px;
    height: 50px;
    fill: grey;
    &:hover{
        fill: red;
    }
}

Tags

Sasschange svg colorreactjavascript

Related Posts

Sass
Text shadows, image shadows and css filters.
July 14, 2020
1 min
React JS
How to add TinyMCE as Rich Text Editor in your React project
May 15, 2021
1 min