Home > Enterprise >  Using SVG from assets folder into component in component folder not working
Using SVG from assets folder into component in component folder not working

Time:02-06

I'm new and still learning ReactJS, one issue that's stumping me is trying to use an SVG image I made in Vectornator from my assets folder to a header component in my component folder. It works fine when I made the mockup in HTML and I didn't had this issue when working on an Angular project last semester. Is there a fix or should I switch back to Angular and give up learning React lol. Also I'm using CRA since I just found out there's a lot of other ways to create a React app, chaos for a later date.

I don't know if it has any issue with folder structure because wherever I put the image it gives me this error. Error Message

This is how my folder structure looks like Folder Structure

And this is my code. I tried doing this through using an img tag and by making the SVG a react component but nothing works to display the image.

import DVLogo from "../assets/DVLogo.svg";
// import {ReactComponent as DVLogo} from "./assets/DVLogo.svg";

const Header = () => {
    return (
        <header className="header">
            {/* <div>
                <DVLogo />
            </div> */}
            <img src={DVLogo} alt="Logo"/>
             <h2 className="header-name">DV</h2>
            <nav>
                <ul className="nav-links">
                    <li><a></a>Search</li>
                    <li><a></a>Collections</li>
                    <li><a></a>About</li>
                    <li><a></a>Decks</li>

                </ul>
            </nav>
            <a className="login-btn"><button>Login</button></a>
        </header>
    );
};

export default Header;

Thanks in advance for any help.

When I use ../ instead of ./

Error #2 part 1

Error #2 part 2

CodePudding user response:

You are not in the correct directory.

When you import your image you need to:

import MyLogo from "../assets/DVLogo.sv" // Note the 2 dots (..)

If you are using the following format:

<img src={DVLogo} alt="Logo"/> // WRONG

You can not pass only DVLogo but also need the src:

<img src={DVLogo.src} alt="Logo"/> // CORRECT

CodePudding user response:

I think it's weird that I'm posting an answer to my own question but maybe it might help someone else or if I forget I can always come back to this. But what I did was create a component returning the actual SVG code and change the syntax of them to match the JSX.

Examples:

stroke-width to strokeWidth

style="fill-rule: nonzero;" to style={{ fillRule: "nonzero"}}

vectornator:layerName="card" to vectornatorlayername="card"

Below is pics of both for a more in-depth look at the differences if anyone is interested. Thank you guys for helping. Not changing majors yet!

Original SVG file

New SVG component

  • Related