Languages
[Edit]
EN

React - how to use svg graphics / icons

5 points
Created by:
Mikolaj
519

In this article, we would like to show you how to use SVG graphics / icons in React.

There are three ways to do this, but in the examples below we will only describe the first two where you don't need additional tools:

  1. Using image tag,
  2. Using svg tag (SVGR conversion),
  3. Using svg file import (assumes webpack use).

1. Using image tag

Below example presents how to use img tag to display svg image from a website.

const App = () => {
  return (
    <div>
      <img src="http://examplewebsite.com/image.svg" />
    </div>
  );
}

2. Using svg tag (SVGR conversion)

To use svg element we need to keep correct property names defined in React - it means we are not able just to paste HTML SVG code without any changes, because it will cause errors. We can correct all by self looking on official React docs or use some tool.

Below example presents how to use SVGR tool to convert your HTML SVG image into React SVG image. The tool returns separated component definition stored in js file for each provided svg file. It is just necessary to run one command line. Check below steps to know how to install the tool and use it:

Step 1: Install SVGR globally using:

npm i -g @svgr/cli

or locally in your project:

npm install @svgr/cli --save-dev

Step 2: convert your HTML SVG image/icon to React component (js file):

npx @svgr/cli --icon icon.svg > icon.js

Step 3: just import the icon file and use it as a component.

import React from "react";
import Icon from "./images/icon.js";

const App = () => {
  return (
    <div>
      <Icon />
    </div>
  );
}

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - svg graphics / icons
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join