React - how to use svg graphics / icons
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:
- Using image tag,
- Using
svg
tag (SVGR conversion), - Using svg file import (assumes webpack use).
Below example presents how to use img
tag to display svg image from a website.
xxxxxxxxxx
const App = () => {
return (
<div>
<img src="http://examplewebsite.com/image.svg" />
</div>
);
}
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:
xxxxxxxxxx
npm i -g @svgr/cli
or locally in your project:
xxxxxxxxxx
npm install @svgr/cli --save-dev
Step 2: convert your HTML SVG image/icon to React component (js file):
xxxxxxxxxx
npx @svgr/cli --icon icon.svg > icon.js
Step 3: just import the icon file and use it as a component.
xxxxxxxxxx
import React from "react";
import Icon from "./images/icon.js";
const App = () => {
return (
<div>
<Icon />
</div>
);
}