Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React CRA - Images Ecosystem

When using create-react-app, in what directory should my images folder be?

in src or public?

Will one or the other present issues when I'm ready to run yarn build?

I heard that only files placed in public directory will be loaded after a build. True or False?

I guess this comment by the react team on index.html has me confused.

    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
        <!--
          Notice the use of %PUBLIC_URL% in the tags above.
          It will be replaced with the URL of the `public` folder 
          during the build.
          Only files inside the `public` folder can be referenced from 
          the HTML.
          Unlike "/favicon.ico" or "favicon.ico", 
          "%PUBLIC_URL%/favicon.ico" will
         work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->

EDIT: After reading the comments below this is how structured my images folder inside the src folder. Can you please tell me if this is a good/best practice?

**Images Component**
import Foo from "./images/foo.jpg";
import Bar from "./images/bar.jpg";
import './styles/Images.css';

export const Logo = () => (
    <img src={Foo} alt="bla bla" />
)
export const Profile = () => (
    <img src={Bar} alt="bla bla" />
)

A component that I want to use the images.

import { Logo, Profile } from './Images';

const Home = () => (
   <div>
    <Logo/>
    <Profile/>
   </div>
)
like image 507
Null isTrue Avatar asked Dec 06 '25 02:12

Null isTrue


1 Answers

You should create a folder under src for the images. Then just use import './myImage.png' as imageThatIsMine to import them into a .js file.

In a .css you would use

.myClass {
  background-image: url('./myImage.png')
}

Doing it this will insure that webpack correctly moves the file to the build folder and appends the correct paths.

See the docs for more info.

If you place anything outside of the src folder and try to import you will get an error telling you to use src.

You can place items in the ;public' folder but it is not recommend. See docs

If you do use the public folder you will need to prefix with %PUBLIC_URL% when you use them.

like image 55
bluesixty Avatar answered Dec 08 '25 15:12

bluesixty