htmlcssreactjscodesandbox

CodeSandbox.io <img> tag not loading image


I have been trying add an image using the <img> tag on CodeSandbox.io. However, every time I try to add it, it doesn't show and just defaults to the alt tag (Displays Mountain).

I am trying to load an image in the same folder as the file in which this JS file is contained.

Below is the code which generates the HTML

function Navbar() {
  return (
    <navbar className="navbar">
      <div>
        <img src="business-landing-page-template-with-photo_52683-19539.jpg" alt="Mountain"/>
      </div>
    </navbar>
  )

Can someone please tell me how to get the image to load.


Solution

  • If in the public folder, use file path relative to it, i.e. public/img/image.jpg, otherwise, if the source image is in your component directories, you use require and relative path:

    Given component in src/components and image is in src/img

    function Navbar() {
      return (
        <navbar className="navbar">
          <div>
            <img
              src={require("../img/business-landing-page-template-with-photo_52683-19539.jpg")}
              alt="Mountain"
            />
            // or in public
            <img
              src="src/img/business-landing-page-template-with-photo_52683-19539.jpg"
              alt="cat"
            />
          </div>
        </navbar>
      )
    }
    

    Edit use local image