Search code examples
javascriptreactjsreactstrap

How can I display my image in a React app?


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!


Solution

  • 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.