2

I am not understanding how import works in React. I'm currently using create-react-app. I have a folder inside components folder named images:

- src
  - components
    - images

Insides the components folder I also have a js file named ProductSquare.js. I am trying to import a picture from images folder using this line

import bumper from './images/bumper1.png';

I have tried changing it to only bumper1.png and many other options. What am I doing wrong here? ( would appreciate a better way to do it in the future).

Is this how programmers import pictures in the real world?

ischenkodv
  • 4,205
  • 2
  • 26
  • 34
user9878643
  • 308
  • 4
  • 15
  • 1
    possible duplicate: https://stackoverflow.com/questions/43823289/how-to-import-image-svg-png-in-a-react-component?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Ethan Ryan Jun 13 '18 at 19:24

4 Answers4

2

Try using <img src={require('./images/bumper1.png')} />

P.S. The similar question goes here

inaumov17
  • 1,329
  • 11
  • 18
1

If you are using something like Webpack (which create-react-app does) then yes, you can just import the images (and most other file types). They end up getting converted into something (I believe images end up as a data URL).

If your folder structure looks like this:

  • src
    • components
    • ProductSquare.js
    • images

Then you should be able to use the image like this:

// in ProductSquare.js
import React from 'react';
import bumper from './images/bumper1.png';

class ProductSquare extends React.Component {
  render() {
    return <img src={ bumper } />;
  }
}

If it isn't, double-check that all of the files are named what you think they should be (check for typos and what not).

If everything is correct and it isn't working, try just adding console.log(bumper) before the class. Then:

  • if it outputs a string that looks like data:blahblah it should work
  • if it outputs undefined, the image may not be named properly
  • if it doesn't output, you might not be using ProductSquare correctly
samanime
  • 25,408
  • 15
  • 90
  • 139
  • I found out that if I do this 'const WPlogo = require('./images/logo.png');' ' const bumper = require('./images/bumper1.png');' – user9878643 Jun 13 '18 at 20:46
1

Using the public Folder

Note: this feature is available with react-scripts@0.5.0 and higher.

Create a folder in public folder, for example, 'image', add your photos there.

After that wherever you want you can use image address like this:

<img className="img1" src="/image/pic.jpg" alt=""/>
Nafis
  • 1,020
  • 17
  • 36
1

You Need to use .default after require

<img src={require('./images/bumper1.png').default} />
Abdul.Moqueet
  • 902
  • 12
  • 19