I have seen lot libraries for svg on react but none gave me how to import a .svg in the react component , I have seen code which talk about bring the svg code in to react ra
There are two ways I want to show you.
The first one is just a simple import of the required SVG.
import MyImageSvg from '../../path/to.svg';
Just remember to use a loader for e.g. Webpack:
{
test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
include: [Path.join(__dirname, "src/assets")],
loader: "file-loader?name=assets/[name].[ext]"
}
Another (and more elegant way) is that you can define an SVG icon sprite and use a component to fetch the correct sprite of the SVG. For example:
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 }) => (
);
Icon.propTypes = {
name: PropTypes.string.isRequired,
color: PropTypes.string,
size: PropTypes.number
};
export default Icon;
The icon sprite (icons.svg) can be defined as:
You can define your own icon sprite on http://fontastic.me/ for free.
And the usage:
And possible add some simple styling for using the icons everywhere:
[class^="icon-"], [class*=" icon-"] {
display: inline-block;
vertical-align: middle;
}