0

I am having trouble loading images in a React app created with create-react-app. Loading the images return a 304 Not Modified response. Here is my code: App.js:

import logo from './logo.svg';
import { Navbar, NavbarBrand } from 'reactstrap'
import Menu from './components/MenuComponent';
import './App.css';

function App() {
  return (
    <div>
      <Navbar dark color="primary">
        <div className="container">
          <NavbarBrand href="/" >Home</NavbarBrand>

        </div>

      </Navbar>

      <Menu />

      <img src="assets/images/uthappizza.png" alt=""/>

    </div>
  );
}

export default App;

Thanks!

Joseph
  • 74
  • 1
  • 7

2 Answers2

2

Looking at https://create-react-app.dev/docs/adding-images-fonts-and-files/, you need to do:

import React from 'react';
import logo from './logo.svg';
import { Navbar, NavbarBrand } from 'reactstrap'
import Menu from './components/MenuComponent';
import './App.css';
import pizza from './assets/images/uthappizza.png'; // Tell webpack this JS file uses this image

function App() {
  return (
    <div>
      <Navbar dark color="primary">
        <div className="container">
          <NavbarBrand href="/" >Home</NavbarBrand>
        </div>
      </Navbar>
      <Menu />
      <img src={pizza} alt=""/>
    </div>
  );
}

export default App;

You can also read more about how WebPack works here.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
Njuguna Mureithi
  • 3,506
  • 1
  • 21
  • 41
  • Thanks. Do I have to import an image every time I need to use an image? Let's say I am receiving multiple image paths from an api/json file, how can I import all of them? – Joseph Dec 16 '20 at 06:37
  • 1
    Yes you can. See this question and answers https://stackoverflow.com/a/42118921/1418750 – Njuguna Mureithi Dec 16 '20 at 06:40
0

This is the right way of importing static assets:

import VariableName from "../relative/path/to/image.png";
import image from './assets/images/uthappizza.png';

The imported variable image contains the full URL relative to the app for assets/images/uthappizza.png . You just need to change to:

import image from './assets/images/uthappizza.png';

<img src={image} alt="Logo" />;
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252