[image] Load local images in React.js

I have installed React using create-react-app. It installed fine, but I am trying to load an image in one of my components (Header.js, file path: src/components/common/Header.js) but it's not loading. Here is my code:

import React from 'react'; 

export default () => {
  var logo1 = (
    <img 
      //src="https://s3.amazonaws.com/codecademy-content/courses/React/react_photo-goose.jpg"
      src={'/src/images/logo.png'}
      alt="Canvas Logo"
    />
  );
  return (
    <div id="header-wrap">
      <div className="container clearfix">
        <div id="primary-menu-trigger">
          <i className="icon-reorder"></i>
        </div>
                    
        <div id="logo">
          <a href="/" className="standard-logo" data-dark-logo='/images/logo-dark.png'>{logo1}</a>
          <a href="/" className="retina-logo" data-dark-logo='/images/[email protected]'>
            <img src='/var/www/html/react-demo/src/images/[email protected]' alt="Canvas Logo" />
          </a>
        </div>
      </div>
    </div>
  );
} 

If I write the image path as src={require('./src/images/logo.png')} in my logo1 variable, it gives the error:

Failed to compile.

Error in ./src/Components/common/Header.js

Module not found: ./src/images/logo.png in /var/www/html/wistful/src/Components/common

Please help me solve this. Let me know what I am doing wrong here.

This question is related to image reactjs local

The answer is


If you want load image with a local relative URL as you are doing. React project has a default public folder. You should put your images folder inside. It will work.

enter image description here


Instead of use img src="", try to create a div and set background-image as the image you want.

Right now it's working for me.

example:

App.js

import React, { Component } from 'react';
import './App.css';



class App extends Component {

  render() {
    return (
      <div>
        <div className="myImage"> </div>
      </div>
    );
  }
}

export default App;

App.css

.myImage {
  width: 60px;
  height: 60px;
  background-image: url("./icons/add-circle.png");
  background-repeat: no-repeat;
  background-size: 100%;
}

First, you need to create a folder in src directory then put images you want.

Create a folder structure like

src->images->linechart.png

then import these images in JSX file

import linechart from './../../images/linechart.png'; 

then you need use in images src like below.

<img src={linechart} alt="piechart" height="400px" width="400px"></img>

Best approach is to import image in js file and use it. Adding images in public folder have some downside:

  • Files inside public folder not get minified or post-processed,

  • You can't use hashed name (need to set in webpack config) for images , if you do then you have to change names again and again,

  • Can't find files at runtime (compilation), result in 404 error at client side.


In React or any Javascript modules that internally use Webpack, if the src attribute value of img is given as a path in string format as given below

e.g. <img src={'/src/images/logo.png'} /> or <img src='/src/images/logo.png' />

then during build, the final HTML page built contains src='/src/images/logo.png'. This path is not read during build time, but is read during rendering in browser. At the rendering time, if the logo.png is not found in the /src/images directory, then the image would not render. If you open the console in browser, you can see the 404 error for the image. I believe you meant to use ./src directory instead of /src directory. In that case, the development directory ./src is not available to the browser. When the page is loaded in browser only the files in the 'public' directory are available to the browser. So, the relative path ./src is assumed to be public/src directory and if the logo.png is not found in public/src/images/ directory, it would not render the image.

So, the solution for this problem is either to put your image in the public directory and reference the relative path from public directory or use import or require keywords in React or any Javascript module to inform the Webpack to read this path during build phase and include the image in the final build output. The details of both these methods has been elaborated by Dan Abramov in his answer, please refer to it or use the link: https://create-react-app.dev/docs/adding-images-fonts-and-files/


You have diferent ways to achieve this, here is an example:

import myimage from './...' // wherever is it.

in your img tag just put this into src:

<img src={myimage}...>

You can also check official docs here: https://facebook.github.io/react-native/docs/image.html


In order to load local images to your React.js application, you need to add require parameter in media sections like or Image tags, as below:

image={require('./../uploads/temp.jpg')}

In React.js latest version v17.0.1, we can not require the local image we have to import it. like we use to do before = require('../../src/Assets/images/fruits.png'); Now we have to import it like = import fruits from '../../src/Assets/images/fruits.png';

Before React V17.0.1 we can use require(../) and it is working fine.


we don't need base64 , just give your image path and dimensions as shown below.

import Logo from './Logo.png' //local path

        var doc=new jsPDF("p", "mm", "a4");
        var img = new Image();
        img.src =Logo;
        doc.addImage(img, 'png', 10, 78, 12, 15)

Examples related to image

Reading images in python Numpy Resize/Rescale Image Convert np.array of type float64 to type uint8 scaling values Extract a page from a pdf as a jpeg How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter? Angular 4 img src is not found How to make a movie out of images in python Load local images in React.js How to install "ifconfig" command in my ubuntu docker image? How do I display local image in markdown?

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to local

Load local images in React.js Access to Image from origin 'null' has been blocked by CORS policy How can I parse a local JSON file from assets folder into a ListView? How to make a local variable (inside a function) global How to securely save username/password (local)? Is it possible to run .php files on my local computer? How to keep the local file or the remote file during merge using Git and the command line? Mocking methods of local scope objects with Mockito Load HTML file into WebView PHP server on local machine?