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
  • 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 "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. Commented May 6, 2020 at 8:29

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

You can try:

import thumbObject from './Angelica05.jpg'

... (in your code)

<img src={thumbObject} />

Hope this helps!

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.