I would explain How to display svg icons(.svg files) in UI using React Component, to add svg icons in UI using React Component to your project file. This article will help you better understand the react architecture as well.
How to display svg icons(.svg files) in UI using React Component?
To display svg icons in UI using React Component, just perform a simple import of the required SVG. You can also define an SVG icon sprite and use a component to search for the correct sprite of the SVG.
Below are the methods to display svg icons(.svg files) in UI using React Component:
Method 1: Do a simple import
The first method is to perform a simple import of the required SVG simply by following the below mentioned code:
import MyImageSvg from '../../path/to.svg';
Make a note to use a loader for example you can use the Webpack loader following the code mentioned below:
{
test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
include: [Path.join(__dirname, "src/assets")],
loader: "file-loader?name=assets/[name].[ext]"
}
Method 2: Define an SVG icon sprite
The second method is that you can define an SVG icon sprite to use as a component to fetch the correct sprite of the SVG. We will show you the correct way to define a SVG icon with the help of an example given below:
//Source: Stackoverflow
import React from "react";
import Icons from "../../assets/icons/icons.svg"; // Path to your icons.svg
import PropTypes from 'prop-types';
const Icon = ({ name, color, size }) => (
<svg className={`icon icon-${name}`} fill={color} width={size} height={size}>
<use xlinkHref={`${Icons}#icon-${name}`} />
</svg>
);
Icon.propTypes = {
name: PropTypes.string.isRequired,
color: PropTypes.string,
size: PropTypes.number
};
export default Icon;
This should give you a proper and in-depth understanding How to display svg icons(.svg files) in UI using React Component.
Conclusion
To display svg icons(.svg files) in UI using React Component, you can just perform a simple import of the required SVG or you can also define an SVG icon sprite and use a component to search for the correct sprite of the SVG.