skip to Main Content

I am currently building a small react webpage and the component I’m building returns one of two images based on whether a certain variable is null or not (it is supposed to hold the link to an image after an api request is made, but starts null). When that link isn’t available the code is supposed to return a different img object with an image locally available "camera.jpg".

Unfortunately it looks like react is trying to call the proxy to my backend for the image even though I define the image with a local path. Any advice on how to fix it?

For reference here are my files

Image of file list for react app

Here is the warning telling me that react is looking in proxy for the image
Proxy error: Could not proxy request '/camera.jpg' from 'localhost:3000' to 'http://localhost:3001/'.

Img html object in code

<img
        id="imgHolder"
        src="./camera.jpg"
        alt="Something went wrong!"
        height="500"
        width="500"
      />

I have tried to look at different sources but I can’t tell if this is a problem with my js code or if I lack an understanding of how the proxy value functions in package.json. I want to see the image pop up but what I get instead is the alt text.

2

Answers


  1. You probably are getting that error because you passed string ./camera.jpg cuz react uses webpack for bundling, and webpack processes assets like images differently.

    Use require() or import:

    import cameraImage from './camera.jpg';
    
    <img
      id="imgHolder"
      src={cameraImage}
      alt="Something went wrong!"
      height="500"
      width="500"
    />
    

    Hope this helps. If not,

    You can place the image in Public folder cuz files in the public folder are served as static files, so you can reference them directly like you are doing in your code.

    <img
      id="imgHolder"
      src="/camera.jpg"
      alt="Something went wrong!"
      height="500"
      width="500"
    />
    

    Edit:

    Btw, The warning you’re seeing says there’s a proxy setup in package.json. http://localhost:3001.

    Login or Signup to reply.
  2. In React, the program is run via index.html and is located in src public, so camera.jpg is moved to public.
    Then call ‘./camera.jpg’.
    It works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search