I want to use svgr's webpack plugin with create-react-app to use SVGs with MaterialUI's SvgIcon. I'm using craco to add svgr to Webpack's config.
Currently, whenever the SVG is supposed to be rendered, the following error is thrown:
Failed to execute 'createElement' on 'Document': The tag name provided ('static/media/googlelogo.03ad8507.svg') is not a valid name.
My craco.config.js:
const CracoAlias = require("craco-alias");
module.exports = {
  plugins: [
    {
      plugin: CracoAlias,
      options: {
        baseUrl: "./src",
        tsConfigPath: "./tsconfig.extend.json",
        source: "tsconfig"
      }
    }
  ],
  webpack: {
    configure: (config, { env, paths }) => {
      config.module.rules.push({
        test: /\.svg$/,
        use: ["@svgr/webpack"]
      });
      return config;
    }
  }
};
How do I embed the SVG properly?
There are a number of ways to use SVG in Create React App. We are going to describe them one by one. SVG can be used in JSX directly. Lines 5-7 define an SVG, which prints out a text: Today is Sunday.
This works because create-react-app uses SVGR under the hood to make it possible to transform and import SVG as a React component. Hope you found this post useful.
Create React App is a fantastic way to get up and running building a web app with React. It also supports using TypeScript with React. Simply entering the following:
Using the img tag is how Create React App embeds the logo SVG, which is defined in a separate file, src/logo.svg. This method is enabled by the built-in file-loader, which is configured by webpack.config.js: Put our text SVG into src/logo.svg: Then it can be invoked as an image in JSX:
It looks like CRA supports converting SVGs by default, thus making craco+svgr redundant.
import { ReactComponent as GoogleLogo } from "../assets/images/googlelogo.svg";
GoogleLogo is a component now.
ReactComponent is a required magic string.
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