Image not getting rendered in react application

659 Views Asked by At

Unable to render images in react, In browser console, image names are displayed correctly but on UI it is not displayed. Also, src attribute is missing from img tag after inspecting element. Please assist. Here is Sample Script

function importAll(r) {
    let images = {};
    r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
    return images;
}

const get_images = importAll(require.context('../../images', true, /\.(png|jpe?g|svg)$/));

const images = Object.entries(get_images).map(module => module[1].default);

return (
    <div className="product">
        <div>
            <Row>
                {products.map(product =>
                    <Col span={6} key={product.productId}>
                        <div >
                            
                            <div>{console.log(product.productImageName)}
                                {<Image src={images[product.productImageName]} width={200} 
height={200} />}
                            </div>
                            
                        </div>
                    </Col>
                )
                }
            </Row>
        </div>
    </div>
)
2

There are 2 best solutions below

0
Parag Diwan On

You don't need to import images. if images are part of your repository then you can use the relative path from the src directory. e.g assuming the images in under src

const path = `images/${[product.productImageName]}`;
<Image src={path} />
1
Paulliano On

You should try and check if profile exist. Like this:

{profile && profile.map((...

//Or

{profile?.map((...