Import SVGs in React
Bring SVGs in React app
Getting Started
Importing SVGs using the image tag is one of the easiest ways to use an SVG. If you initialize your app using CRA (Create React App), you can import the SVG file in the image source attribute, as it supports it off the bat.
import YourSvg from "/path/to/image.svg";
const App = () => {
return (
<div className="App">
<img src={YourSvg} alt="Your SVG" />
</div>
);
};
export default App;
But if you are not using CRA, you have to set up a file loader system in the bundler you're using (Webpack, Parcel, Rollup, and so on).
Webpack, for instance, has a loader for handling SVGs called file-loader.
To install the file-loader, add the following command:
npm install file-loader --save-dev
Next, add the loader to the webpack.config.js file:
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif)$/i,
use: [
{
loader: "file-loader",
},
],
},
],
},
};
Now, you can import your SVG files and use them:
import YourSvg from "/path/to/image.svg";
const App = () => {
return (
<div className="App">
<img src={YourSvg} alt="Your SVG" />
</div>
);
};
export default App;
Note: While this approach is straightforward, it does have one disadvantage: unlike the other methods for importing, you cannot style the SVG imported in a img element. As a result, it will be suitable for an SVG that does not need customization, like logos.
Connect with me ^_^
If you like this article, kindly follow my github account for more and be sure to ⭐ it.