[javascript] ReactJS and images in public folder

Im new in ReactJS and I want to import images in a component. These images are inside of the public folder and I do not know how to access the folder from the react component.

Any ideas ?

EDIT

I want to import an image inside Bottom.js or Header.js

The structure folder is:

enter image description here

I do not use webpack. Should I ?

Edit 2

I want to use webpack for loading the images and the rest of assets. So in my config folder I have the next files:

enter image description here

Where I need to add the paths of the images and how?

Thanks

This question is related to javascript reactjs

The answer is


the react docs explain this nicely in the documentation, you have to use process.env.PUBLIC_URL with images placed in the public folder. See here for more info

return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />;

You should use webpack here to make your life easier. Add below rule in your config:

const srcPath = path.join(__dirname, '..', 'publicfolder')

const rules = []

const includePaths = [
  srcPath
]
    // handle images
    rules.push({
      test: /\.(png|gif|jpe?g|svg|ico)$/,
      include: includePaths,
      use: [{
        loader: 'file-loader',
        options: {
          name: 'images/[name]-[hash].[ext]'
        }
      }

After this, you can simply import the images into your react components:

import myImage from 'publicfolder/images/Image1.png'

Use myImage like below:

<div><img src={myImage}/></div>

or if the image is imported into local state of component

<div><img src={this.state.myImage}/></div> 

We know React is SPA. Everything is rendered from the root component by expanding to appropriate HTML from JSX.

So it does not matter where you want to use the images. Best practice is to use an absolute path (with reference to public). Do not worry about relative paths.

In your case, this should work everywhere:

"./images/logofooter.png"


1- It's good if you use webpack for configurations but you can simply use image path and react will find out that that it's in public directory.

<img src="/image.jpg">

2- If you want to use webpack which is a standard practice in React. You can use these rules in your webpack.config.dev.js file.

module: {
  rules: [
    {
      test: /\.(jpe?g|gif|png|svg)$/i,
      use: [
        {
          loader: 'url-loader',
          options: {
            limit: 10000
          }
        }
      ]
    }
  ],
},

then you can import image file in react components and use it.

import image from '../../public/images/logofooter.png'

<img src={image}/>

You Could also use this.. it works assuming 'yourimage.jpg' is in your public folder.

<img src={'./yourimage.jpg'}/>

You don't need any webpack configuration for this..

In your component just give image path. By default react will know its in public directory.

<img src="/image.jpg" alt="image" />