I am wondering how to set up an inline svg with webpack?
I am following the react-webpack-cookbook.
I have my webpack.config set up correctly with the file loader.
However the example shows using a background image like this:
.icon { background-image: url(./logo.svg); }
which works fine, but I want to have an inline svg image how do I do this to include my logo.svg inline in my react component?
import React, { Component } from 'react' class Header extends Component { render() { return ( <div className='header'> <img src={'./logo.svg'} /> </div> ); } }; export default Header
Once you start your application, Webpack will do its thing and you don't need to worry about your SVGs anymore. You can put your SVG files anywhere in your src/ folder and import them wherever you need them as React components. This method is generally referred to as inline-svg .
How to use inline SVG images. SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document.
This Webpack loader inlines SVG as module. If you use Adobe suite or Sketch to export SVGs, you will get auto-generated, unneeded crusts. This loader removes it for you, too.
Inline SVGs have many advantages over externally embedded SVG files. Above all, the interaction with CSS is significantly easier, as SVG can be treated the same way all other elements of your document are treated via CSS. This is a decisive advantage, especially for interactions like hover effects.
Actually Michelle's answer pointed me in the right direction, and that works nicely for loading an svg file with webpack and using it as your <img>
src
However to actually get the inline svg, I needed to do the following:
Instead of file-loader use svg-inline-loader as your svg loader:
{ test: /\.svg$/, loader: 'svg-inline-loader' }
Then to load the svg inline in a component:
import React, { Component } from 'react' import logo from "./logo.svg"; class Header extends Component { render() { return ( <div className='header'> <span dangerouslySetInnerHTML={{__html: logo}} /> </div> ); } }; export default Header
It looks like there is an inline svg wrapper for react svg-inline-react which would be another option instead of the <div dangerouslySetInnerHTML={{__html: mySvg}} />
Here is a simple non-react solution.
{ test: /\.svg$/, loader: 'svg-inline-loader' }
import Svg from './svg.svg'; function component() { const element = document.createElement('div'); element.innerHTML = Svg; return element; } document.body.appendChild(component());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With