{Solved} Local images not loading in React application

Hello everyone and welcome to my blog.

Through my blog I share interesting tips and discuss on latest releases on Microsoft.NET technologies, Dynamics 365 and Power Platform, SharePoint and Client scripting libraries. Please subscribe to my blog to stay updated.

In today’s blog I will discuss about a very common problem that you may encounter when you build a React application that show local image files.

Let’s jump into the problem here. I have a React project and inside the components folder, I have an image file – xrmforyou.png and a .js file – banner.js.

In the banner.js file, I have added a reference to my image file. Below is the code of banner.js

Everything is expected to work fine but unfortunately when I run my React app, the image does not show up.

The usual recommendations to resolve this error are to either import the file and then refer the image file or use the require() function to load the image file.

In the below code, I used the import statement to import the image file and then refer it in my code. Unfortunately it didn’t work.

import logo from './xrmforyou.png'
const Banner = () => {
    return (
        <header>
            <div>
                <img src="{logo}" alt="logo" />
            </div>
            <h1>
                Welcome to XRMFORYOU Consulting Private Limited
            </h1>
        </header>
    )
};

export default Banner;

Even tried the require() function and it didn’t work too.

const Banner = () => {
    return (
        <header>
            <div>
                <img src="{require('./xrmforyou.png')}" alt="logo" />
            </div>
            <h1>
                Welcome to XRMFORYOU Consulting Private Limited
            </h1>
        </header>
    )
};

export default Banner;

After extensive googling and trial and error, finally found the solution. React project has a public folder where you can keep your images.

Once it is placed in there, you can refer to the file using relative path. So if you file is directly under the Public folder, you can refer it directly. Example code below.

<img src="./xrmforyou.png'" alt="logo" />

If it is placed inside a folder within the public folder, you need to specify the folder in the relative path URL. For example – If your file is placed is placed within the images folder inside the public folder, you can use like below.

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

After making these changes, when you run the app, the image will show up.

Hope this helped. Please subscribe to my blog for more interesting topics like this.

You will also like the below posts.

Debajit Dutta
Business Solutions MVP