how to set up an inline svg with webpack

84,612

I hope my late answer will still be useful for someone, because I don't like any of abovementioned options.

The react-svg-loader webpack loader allows you to import SVG icons like JSX components:

import Logo from './logo.svg';

class App extends Component {
  render() {
    return (
      <div className="App">
          <Logo fill="red" className="logo" width={50} height={50} />
      </div>
    );
  }
}

and minimum config looks like this:

{
  test: /\.svg$/,
  use: [
    {
      loader: "babel-loader"
    },
    {
      loader: "react-svg-loader",
      options: {
        jsx: true // true outputs JSX tags
      }
    }
  ]
}

The best part is that it just outputs the svg file contents, without any extra wrappers and dangerouslySetInnerHTML in your code.

Share:
84,612
svnm
Author by

svnm

javascript, ruby, css

Updated on July 13, 2022

Comments

  • svnm
    svnm almost 2 years

    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
    
  • Greg
    Greg over 4 years
    This works perfect with latest React 16.10 and Webpack 4.41. Thanks!