react won't load local images

  • Last Update :
  • Techknowledgy :

4 This usually means your local web server is not serving the images or the url you specified is incorrect. Open your browser console and check if you get any errors such as 404 not found. – Mario Tacke Jan 3, 2016 at 22:35 First, Check whether you have specified the current location of the image or not, if you face difficulties setting the correct path , you can use this. First, Check whether you have specified the current location of the image or not, if you face difficulties setting the correct path , you can use this.

This is our Splunktool team suggestion ✌, we tried and its working fine
instead of <img src={"/images/resto.png"} /> you need to use <img src={require('/images/image-name.png')} />

I started building my app with create-react-app (see "Create a New App" tab). The README.md that comes with it gives this example:

import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image

console.log(logo); // /logo.84287d09.png

function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />;
}

export default Header;

Suggestion : 2

Images don't load neither when using npm run start or npm run build Chrome console in both cases indicate something is wrong with paths. Imgur And when you need to use the image, you can import this in your app.jsx for example and usage in all of rest files, that is cool :) The first value 'images' are from the outputPath value and the second are the name of the file... The question is how I need to configure Webpack to do this manually?! What settings are responsible for this functionality?

Project was created without using npx create-react-app.

My App.js

import React, { Component } from 'react'

class App extends Component {
    render() {
        return (
            <div>
                <h1>Testing Webpack with images</h1>
                <img src={require("./images/img1.jpg")} alt="cannot display"/>
                <img src="images/img1.jpg" alt="cannot display"/>
            </div>
        )
    }
}

But paths should be fine. My project structure: Imgur

My NPM scripts:

"scripts": {
   "start": "webpack-dev-server --open --config webpack.config.js",
   "build": "webpack --config webpack.config.js"
}

and finally webpack.config.js:

const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require("path");

module.exports = {
   entry: "./src/index.js",
   output: {
      path: path.resolve(__dirname, "dist"),
      filename: "[name].[hash].js"
   },
   module: {
      rules: [{
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
               loader: "babel-loader"
            }
         },
         {
            test: /\.html$/,
            use: ["html-loader"]
         },
         {
            test: /\.(jpg|png|svg|gif)$/,
            use: {
               loader: "file-loader",
               options: {
                  name: "[name].[hash].[ext]",
                  outputPath: "imgs"
               }
            }
         }
      ]
   },
   plugins: [
      new HtmlWebPackPlugin({
         template: "./src/index.html"
      })
   ]
}

If I try to change it to <img src={require("./imgs/img1.jpg")} /> (tried also these paths /imgs/, imgs/) in all cases then I get compilation error:

ERROR in . / src / App.js
Module not found: Error: Can 't resolve '. / imgs / img1.jpg ' in
'/home/juris/Documents/My Projects/playground/webpack-images/src'

Eyy wsp, after a couple of work, i have the solve i think...

First the webpack file-loader configuration:

{
   use: {
      loader: 'file-loader',
      option: {
         limit: false,
         name: '[name]', //You can add '.[ext]' for specify the file type
         outputPath: 'images/' //Define the final path...
      }

   },
   test: /\.(jpe?g|png|gif|svg)$/i,
}

Suggestion : 3

When using Webpack you need to require images in order for Webpack to process them, which would explain why external images load while internal do not, so instead of <img src={"/images/resto.png"} /> you need to use <img src={require('/images/image-name.png')} /> replacing image-name.png with the correct image name for each of them. That way Webpack is able to process and replace the source img. This worked perfectly for me. Here's a link to the master doc for that README, which explains (excerpt): To reduce the number of requests to the server, importing images that are less than 10,000 bytes returns a data URI instead of a path. This applies to the following file extensions: bmp, gif, jpg, jpeg, and png...

I am building a small react app and my local images won't load. Images like placehold.it/200x200 loads. I thought maybe it could be something with the server?

Here is my App.js

import React, { Component } from 'react';

class App extends Component {
    render() {
        return (
            <div className="home-container">
                <div className="home-content">
                    <div className="home-text">
                        <h1>foo</h1>
                    </div>
                    <div className="home-arrow">
                        <p className="arrow-text">
                            Vzdelání
                        </p>
                        <img src={"/images/resto.png"} />
                    </div>
                </div>
            </div>
        );
    }
}

export default App;

index.js:

import React, { Component } from 'react';
import { render } from 'react-dom';
import { Router, Route, Link } from 'react-router';
import { createHistory } from 'history';
import App from './components/app';

let history = createHistory();

render(
    <Router history={history} >
        <Route path="/" component={App} >
            <Route path="vzdelani" component="" />
            <Route path="znalosti" component="" />
            <Route path="prace" component="" />
            <Route path="kontakt" component="" />
        </Route>
        <Route path="*" component="" />
    </Router>,
    document.getElementById('app')
);

and server.js:

var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');

var app = express();
var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
   noInfo: true,
   publicPath: config.output.publicPath
}));

app.use(require('webpack-hot-middleware')(compiler));

app.get('*', function(req, res) {
   res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(3000, 'localhost', function(err) {
   if (err) {
      console.log(err);
      return;
   }

   console.log('Listening at http://localhost:3000');
});

Suggestion : 4

Many of the images you will display in your app will not be available at compile time, or you will want to load some dynamically to keep the binary size down. Unlike with static resources, you will need to manually specify the dimensions of your image. It's highly recommended that you use https as well in order to satisfy App Transport Security requirements on iOS. Local Filesystem ImagesBest Camera Roll Image See CameraRoll for an example of using local resources that are outside of Images.xcassets.

1._
<Image source={require('./my-icon.png')} />
2._
.├──button.js└── img├── check.png├──[email protected].png└──[email protected].png
3._
<Image source={require('./img/check.png')} />
5._
<Image  source={{ uri: 'app_icon' }}  style={{ width: 40, height: 40 }}/>
6._
<Image  source={{ uri: 'asset:/app_icon.png' }}  style={{ width: 40, height: 40 }}/>

Suggestion : 5

First, Check whether you have specified the current location of the image or not, if you face difficulties setting the correct path , you can use this. First, Check whether you have specified the current location of the image or not, if you face difficulties setting the correct path , you can use this. In addition to the accepted answer, you can make your own life a bit easier by specifying an alias path in Webpack, so you don't have to worry where the image is located relative to the file you're currently in. Please see example below:

in the same images folder include a js file which exports all the images, and in components where you need the image import that image and use it :), Yaaah thats it, lets see in detail

folder structure with JS file

// js file in images folder
export const missing = require('./missingposters.png');
export const poster1 = require('./poster1.jpg');
export const poster2 = require('./poster2.jpg');
export const poster3 = require('./poster3.jpg');
export const poster4 = require('./poster4.jpg');

Try changing the code in server.js to -

app.use(require('webpack-dev-middleware')(compiler, {
   noInfo: true,
   publicPath: config.output.path
}));

Sometimes you may enter instead of in your image location/src: try

. / assets / images / picture.jpg
5._
src = {
   "/images/resto.png"
}

When I got the error, I thought it may be related to path issue as in absolute vs relative. So I passed a hard-coded value to require like below: <img src={require("../assets/images/photosnap.svg")} alt="" />. It was working fine. But in my case the value is a variable coming from props. I tried to pass a string literal variable as some suggested. It did not work. Also I tried to define a local method using switch case for all 10 values (I knew it was not best solution, but I just wanted it to work somehow). That too did not work. Then I came to know that we can NOT pass variable to the require.

As a workaround I have modified the data in the data.json file to confine it to just the name of my image. This image name which is coming from the props as a String literal. I concatenated it to the hard coded value, like so:

import React from "react";

function JobCard(props) {  

  const { logo } = props;
  
  return (
      <div className="jobCards">
          <img src={require(`../assets/images/${logo}`)} alt="" /> 
      </div>
    )
} 
  


Suggestion : 6

Download the image and move it into your src directory. To display an image from a URL, use the img tag and set its src prop to the complete URL of the image. Optionally set the alt prop to a short description of the image. To display an image from a local path in React: Import the image into your file, e.g. import MyImage from './thumbnail.webp'.

1._
Copied!import React from 'react';

export default function App() {
  return (
    <div>
      <img
        src="https://bobbyhadz.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp"
        alt="car"
      />
    </div>
  );
}
2._
Copied!import React from 'react';

import MyImage from './thumbnail.webp';

export default function App() {
  return (
    <div>
      {/* 👇️ local image */}
      <img src={MyImage} alt="horse" />

      {/* 👇️ external image */}
      <img
        src="https://bobbyhadz.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp"
        alt="car"
      />
    </div>
  );
}

Suggestion : 7

image not loading, require image typescript, typescript load image It seems you’re using create-react-app and you used require to import your images. In the latest version of CRA, require returns an ES module instead of a string because in file-loader the esModule option is enabled by default. require results in [Object module] instead of the image URL in CRA 4 but not CRA 3 if you clone, change the react-scripts version to 3, and then rerun, the React logo loads perfectly. If you make no changes to the git repo, you’ll see that the logo doesn’t load.

1._
Environment Info:

   current version of create - react - app: 3.4 .1
running from / Users / suman / .config / yarn / global / node_modules / create - react - app

System:
   OS: macOS 11.0
CPU: (4) x64 Intel(R) Core(TM) i5 - 5350 U CPU @ 1.80 GHz
Binaries:
   Node: 12.14 .1 - /usr/local / bin / node
Yarn: 2.2 .2 - /usr/local / bin / yarn
npm: 6.14 .8 - /usr/local / bin / npm
Browsers:
   Chrome: 85.0 .4183 .121
Firefox: 81.0
Safari: 14.0 .1
npmPackages:
   react: Not Found
react - dom: Not Found
react - scripts: Not Found
npmGlobalPackages:
   create - react - app: Not Found
const image = require('../path/to/image.jpg').default;
// OR
import image from '../path/to/image.jpg';

I ended up having to update a bunch of files to add .default after require(). I found them like this:

find src - type f - print0 | xargs - 0 grep--color "require('.*')[^(\.default)]"