0

Trying to import image into a React component. It works if I reference the file directly. But not if I call it from an object. I have tried with the require() and using {} variations but just guessing now.

This works:

import React from 'react';
import './Thumb.css';

const thumbObject = {
    imageSrc: './Angelica05.jpg',
    filename: 'Angelica05.jpg'
}

class Thumb extends React.Component {
    render () {
        return (
            <div className="thumbbox">
                <div className="thumbimage">
                    <img src={require('./Angelica05.jpg')} alt=''/>
                </div>
                <h2>{thumbObject.filename}</h2>
            </div>
        )
    }
} 

export default Thumb;

This doesn't work

import React from 'react';
import './Thumb.css';

const thumbObject = {
    imageSrc: './Angelica05.jpg',
    filename: 'Angelica05.jpg'
}

class Thumb extends React.Component {
    render () {
        return (
            <div className="thumbbox">
                <div className="thumbimage">
                    <img src={require(thumbObject.imageSrc)} alt=''/> //This is the line I can't get working.
                </div>
                <h2>{thumbObject.filename}</h2>
            </div>
        )
    }
} 

export default Thumb;
  • 1
    It seems to be that when you specify the location in the file, if the image is under 10,000 bytes, it copies it to another folder and creates a data URL. So the url is changed to "http://localhost:3000/static/media/Angelica05.8ec4647a.jpg". So specifying it with an object doesn't work when Webpack compiles it. I'm trying to work out another way of doing it. – deepfunk9 May 06 '20 at 08:29

2 Answers2

1

I think webpack doesn't understand the context when it tries to require a module which is not an absolute path at the time of building. I have read that you could use string interpolation to evaluate the value but personally haven't tried it.

Check this out. https://stackoverflow.com/a/45272215/5686257

  • 1
    I think you’re on the right track. The errors are pointing to that it can’t find the image. But it’s in the same directory of the file. I have had a look through that thread and that’s how I got the require(). But it doesn’t seem to work from an object. Thank you for replying. – deepfunk9 May 05 '20 at 21:20
0

You can try:

import thumbObject from './Angelica05.jpg'

... (in your code)

<img src={thumbObject} />

Hope this helps!

Max Wu
  • 136
  • 2
  • 4
  • 1
    Thank you. That is an option. But I’m creating a component to automate bringing in lots of images. Hence creating the object to test with. – deepfunk9 May 05 '20 at 21:18