Home > AI > Frontend > ReactJS >

load local image

Example 1: (image is located in the component and needs dynamical loading)

<img src={require("./images/mn_tea_head_" +props.index + ".jpg").default} alt="" />

Attention: you need to add .default after require. Or you can config your webpack.config.js

{
        test: /\.(png|jpe?g|gif)$/i,
        use: [
          {
            loader: 'file-loader',
            options: {
              esModule: false,
            },
          },
        ],
      },

For more information, you can check this post.

https://stackoverflow.com/questions/59070216/webpack-file-loader-outputs-object-module

Advantage: this method allows you to dynamic load image.

Example 2: image is located in the component and doesn’t need dynamic loading.

import logo from './images/logo.png'

Example 3: image is located in the public folder

<img src="/images/logo.png" alt="" />

Leave a Reply