2

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.

2
  • 1
    Is "business-landing-page-template-with-photo_52683-19539.jpg" in the public folder?
    – Drew Reese
    Apr 28, 2020 at 6:10
  • Sorry, I made a mistake with my last comment. No it is not in public folder. It is in a seperate folder called src. This JavaScript file is located at src/components, and my image is located at src/img
    – AwesomeGuy
    Apr 28, 2020 at 6:13

1 Answer 1

6

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

8
  • What does require do? Apologies, I am new to JS. Why does it work?
    – AwesomeGuy
    Apr 28, 2020 at 6:18
  • what if images are dynamically uploaded?
    – Sachin
    Apr 28, 2020 at 6:32
  • 2
    @AwesomeGuy Honestly I wish a had a decent answer for that question, but it's just the way to specify local image src urls. The other option is to import it at the top of the file and use directly, i.e. import image from './business-landing-page-template-with-photo_52683-19539.jpg', then <img src={image}...`
    – Drew Reese
    Apr 28, 2020 at 6:35
  • 1
    @MattoMK Do you mean like this? codesandbox.io/s/… If so, then yes, you can.
    – Drew Reese
    Oct 19, 2020 at 15:45
  • 1
    @MattoMK That I don't know off the top of my head. Codesandbox runs in an iframe (AFAIK) so has some cross-site/domain restrictions. Seems like a good candidate for another SO question; someone else may have an answer for you more quickly than I could research it.
    – Drew Reese
    Oct 19, 2020 at 18:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.