Search code examples
javascriptreactjsimagesrc

Image not loading when passing a prop to <img src="this.prop." /> in React


I have an issue regarding a link not loading my image when I pass a prop to the attribute src of img. I have tried wrapping require() around my links and it didn't work.

I have a huge library of products which would be unfeasible to manually import images using the image loader.

Therefore, is there a way to load an image using props inside the src attribute?

I am using NODE_PATH=src/

Thanks for the help!

export const productLib = [{
    ID: "001",
    name:"product name",
    src: "lib/productLib/img/product_name",
    color: "",
    ...
    }, {...}]
import React from 'react';

export class Products extends React.Component {
    render() {
        return(
            <div className="products">
                <img src={this.props.product.src} width="50" />
                <h6>{this.props.product.name}<span className={`block ${this.props.product.color}`}></span></h6>
            </div>
        )
    }
}


Solution

  • As recommended by Xuscrus, I linked my images using the public path. I had to remove my absolute path in order for this solution to work.

    I moved all of my images inside a folder named "img" inside the public folder of my create-react-app.

    With the example used in my initial statement, here is the easiest solution I found:

    import React from 'react';
    
    export class Products extends React.Component {
        render() {
            return(
                <div className="products">
                    <img src={`/img/${this.props.product.src}.png`} width="50" />
                    <h6>{this.props.product.name}<span className={`block ${this.props.product.color}`}></span></h6>
                </div>
            )
        }
    }

    My main reference for my solution was this post (URL method in the correct answer) :

    How to do Dynamic images in ReactJS?