Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React SVG tag name provided is not valid

I'm attempting to add an SVG to a React app (built with create-react-app). When I try to add it as a component, I get an error like this:

InvalidCharacterError: Failed to execute 'createElement' on 'Document': The tag name provided ('/static/media/logo.8d229b2c.svg') is not a valid name.

What am I missing?

Code:

import React from 'react';
import Logo from '../img/logo.svg';

const Header = () => {
    return (
        <div>
            <Logo />
        </div>
    )
}

export default Header;
like image 234
tjr226 Avatar asked Apr 03 '20 16:04

tjr226


2 Answers

You can import it this way:

import { ReactComponent as Logo } from '../img/logo.svg';

as said in CRA (create-react-app) documentation

an render it the way you want:

import React from 'react';
import { ReactComponent as Logo } from '../img/logo.svg';
const Header = () => {
    return (
        <div>
            <Logo />
        </div>
    )
}

And also, if it's not necessary to render it as a component, you could just render your svg as an image this way:

import React from 'react';
import logo from '../img/logo.svg';

const Header = () => {
    return (
        <div>
            <img src={logo} alt="logo"/>
        </div>
    )
}

export default Header;
like image 177
Shotiko Topchishvili Avatar answered Sep 20 '22 21:09

Shotiko Topchishvili


You need to import the component using this syntax:

import { ReactComponent as Logo } from '../img/logo.svg';

Using the curly braces and ReactComponent is necessary - they tell React that you want to build a component with the SVG.

I only found this because of a Dan Abramov reply to a create-react-app issue. The link he posted in his comment no longer works, but it's still mentioned in the docs.

https://github.com/facebook/create-react-app/issues/5293

https://create-react-app.dev/docs/adding-images-fonts-and-files/

like image 37
tjr226 Avatar answered Sep 21 '22 21:09

tjr226