How to disable special handling of SVG imports in codesandbox?

Viewed 832

I've created a simple app with create-react-app. This configures webpack loaders for svg files to copy the files and put a public file into the constant. So the following code

import mysvg from "./img/my.svg";
console.log(mysvg)

prints /static/media/my.svg. That's fine.

But when editing/running the same project in codesandbox it tries to read the svg file (e.g. printing errors about ReactComponent if it's not a proper svg), and makes the handling different. Obviously, I could use the "public" folder instead, but I'd like to use the hash feature of production builds etc.

So my question is, how can I allow to use the same mechanism to get a resolving url path (e.g. valid for img src) in codesandbox and use the default create-react-app configuration?

3 Answers

I did some digging, and I think this is definitely a bug with codesandbox.

When we use a .png image, the string path looks like this:

path: https://uploads.codesandbox.io/uploads/user/ff71cfab-643a-41c7-8358-d13e8ce686c9/U6zD-unsplash1.png

But when we use an SVG, things fail.

Some similar issues opened on their github repo: #1664, #3825.

The maintainer said that svg-react-loader is included in CRA v2 template, and you can import them as ReactComponent, I assume this is what you were talking about initially. I think this is what caused svg files to be treated differently by codesandbox.

For now, I guess you can do this hacky workaround:

import mysvg from "!raw-loader!./img/my.svg.txt";

// inside render
<span dangerouslySetInnerHTML={{ __html: mysvg }} />

sandbox here

You would need to add raw-loader as dependency and rename the file to .txt extension so that it doesn't get handled like an .svg.

Long term, I think the best we could do is to participate in #3825 and hope that this can get fixed by codesandbox.

If you're want to use svg images,only importing them as React Components, like this,import {ReactComponent as MySvg} from './img/my.svg' usually always works. There are other ways as well but I think this one is simplest. Check out my solution - myVersionOfCodesandbox

Related