Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding svgr to create-react-app via craco

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?

like image 552
John Smith Avatar asked Feb 05 '20 10:02

John Smith


People also ask

How to use SVG in create react app?

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.

Why create-react-app uses svgr?

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.

What is createcreate react app?

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:

How to embed a logo in a react app?

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:


1 Answers

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.

like image 60
John Smith Avatar answered Oct 04 '22 00:10

John Smith