0

So, I wanted to get an image from my local computer into my app in ReactJS. So, inquiring this: How do I reference a local image in React?, I did this code:

import Header from './components/Header'

function App() {
  return (
    <div className="container">
      <Header />
      <img src={"./resources/faces/face_1.jpg"} alt="A face" />
    </div>
  );
}

export default App;

It doesn't work, so does this:

import Header from './components/Header'

function App() {
  return (
    <div className="container">
      <Header />
      <img src={require("./resources/faces/face_1.jpg")} alt="A face" />
    </div>
  );
}

export default App;

I searched on what could be the reason, like these links:

Not working: require('react/addons')

and others like it, that doesn't apply to me since I'm working with a jpg file.

Later, I tried importing instead of requiring, so:

import Header from './components/Header'
import g from "./resources/faces/face_1.jpg"

function App() {
  return (
    <div className="container">
      <Header />
      <img src={g} alt="A face" />
    </div>
  );
}

export default App;

And it works! However, it is not ideal, since I plan on working with multiple images. I just can't figure out why importing works and requiring doesn't. Thus the question: Why does the require keyword not working, but importing does, in ReactJS?

Thanks in advance.

  • 1
    Using `import './path/image.jpg'` will create a reference to the file and return the correct path. The file will also be included in your build directory which can be deployed to your webserver. Using `require` you will need to add `.default` like so `require('./path/image.jpg').default`. Without import/require you will need an absolute path to the file on your machine. – Chris Sep 03 '21 at 08:56

0 Answers0