Skip to content Skip to sidebar Skip to footer

Src/images Folder In Create-react-app

I have an app scaffolded using create-react-app. I would like to have the folder structure like this: src/ components/ CustomAppBar.js images/ logo.svg App.js index

Solution 1:

What I normally do for assets under /public/assets i import my files then in my react components using src i can access them using process.env.PUBLIC_URL + '/assets/{ENTER REST OF PATH HERE}'

here is a code sample how I implement it.

importReact, { Component } from'react';

const iconPath = process.env.PUBLIC_URL + '/assets/icons/';

exportdefaultclassTestComponentextendsComponent {
    constructor(props) {
        super(props);
    }
    render(){
    return (<imgsrc={`${iconPath}icon-arrow.svg`}
        alt="more"
    />)
    }
}

Here is the link that got me started implementing it this way. https://github.com/facebook/create-react-app/issues/2854

I also noticed you are importing logo incorrectly and should be import logo from '../images/logo.svg' or if logo.svg does not have an export default you should be using import {logo} from '../images/logo.svg'

Solution 2:

You can use ES6 import to locate any file (images, audio, etc) from the root folder and add them to your app.

importReactfrom'React'import errorIcon from'./assets/images/errorIcon.svg'import errorSound from'./assets/sounds/error.wav'classTestComponentextendsReact.Component 
{ 
    render() 
    {
        return (

            <div><imgsrc={errorIcon }
                     alt="error Icon" /><audiosrc={errorSound } /></div>
        )
    }
}

Post a Comment for "Src/images Folder In Create-react-app"