solarflare
solarflare

Reputation: 1092

react: Failing to load an image from a local api path

This might be a very basic one, but for some reason only the first tag loads the image, while the other two do not. I've included the 'require' function as I've seen in other threads, but still to no success. My use-case is loading these paths from an api that's run locally, and has URI references to images also stored locally. These paths are outside of the project directory of my react app. i.e:

Any idea how to make this work?

import React from "react";
import logo from "../my-icon.jpg"


class App extends React.Component {

    render(){
        return (
            <div>
                <img src={logo}/> # WORKS
                <img src={"/Users/my-user/repos/app/python-backend/images/my-icon.jpg"}/> # DOESN'T WORK
                <img src={require("/Users/my-user/repos/app/python-backend/images/my-icon.jpg")}/> # DOESN'T WORK
            </div>
        )
    }
}

export default App;

Upvotes: 1

Views: 355

Answers (1)

David
David

Reputation: 218877

You seem to be confusing two separate things here:

  1. How the React code imports a file and uses it in JSX markup, ultimately creating the resulting HTML markup.
  2. How the browser uses that resulting HTML markup.

When you do this:

import logo from "../my-icon.jpg"

// and later...
<img src={logo}/>

The resulting src value in the HTML will have been translated into something else entirely. The build process for the application knows that my-icon.jpg needs to be included in the bundled build output, and the src value will be a relative URL to that resulting resource.

But when you do this:

<img src={"/Users/my-user/repos/app/python-backend/images/my-icon.jpg"}/>

The build process doesn't have anything to change. You've provided it with a literal string, which will be the exact output in the resulting HTML.

However, according to the problem you've observed, the literal string you're providing here is not the relative URL of the file. The /Users part of this suggests that this is likely a file system path on your C:\ drive. The web server and the file system are two entirely different things.

If you're providing a string value as the src, it will need to be a correct URL to the image file in the build output of the application.

How are you including that file in your application? Does this images folder which contains the file get included in your resulting website? If so then /images/my-icon.jpg may work. But ultimately, if you're getting these string values from data, then you're going to have to determine how the resulting web application can reference the files indicated by that data.

Upvotes: 2

Related Questions