Santeau
Santeau

Reputation: 977

React reference local image with absolute path with react

I'm building a simple desktop app using tauri, with a rust backend and a react frontend. I'm passing the absolute path to a local image (on my device) from the backend to the frontend, and trying to use that path to display the image, but every time, the image isn't loaded and the console looks for the image inside the app folder:

Inspect element: Sources

I tried different things but I haven't been able to find a way that works for me to make sure the path given is interpreted as an absolute path, do you have any solution to suggest?

Upvotes: 2

Views: 690

Answers (1)

haptn
haptn

Reputation: 987

I've just play around and found that ReactJS default doesn't allow us to import any resources outside our app's folder.

As I tried to import an img via an absolute path from C:/ on my device, React returned this error:

Module not found: Error: You attempted to import C:/Users/admin/Pictures/Screenshots/a.png which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.

So the only way I've found so far is to load the image as a base64 string, there are 2 ways to achieve that:

  • Import img as a ES6 module
  • Use <img src={require(...) />

Notice: If you paste your absolute path of the img to browser's address bar then double click it, you can see the "full path" of the img file with the prefix file:///.

Please refer to my example code below:

import React from 'react';
import imgSrc from 'file://C:/Users/admin/Pictures/Screenshots/a.png';

export const Demo = () => {
  return (
    <div className='test-import-img-from-device'>
      <img src={imgSrc} />
      &nbsp; &nbsp; It worked
      <br /><br />

      <img src={require('file://C:/Users/admin/Pictures/Screenshots/a.png')} />
      &nbsp; &nbsp; It also worked
      <br /><br />

      <img src={'C:/Users/admin/Pictures/Screenshots/a.png'} />
      &nbsp; &nbsp; Not worked
      <br /><br />

      <img src={'file://C:/Users/admin/Pictures/Screenshots/a.png'} />
      &nbsp; &nbsp; Also not worked
    </div>
  )
}

Result: enter image description here


In your case, I think <img src={require('file://...') /> would solve your issue.

Hope this can help!

Upvotes: 2

Related Questions