Home > database >  local image doesn't appear using require react js
local image doesn't appear using require react js

Time:10-01

I tried to get dynamically the directory of the images using require but doesn't work

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


function Produto({data}) {

    const { id, name, price, score, image } = data;

    return <div className = 'produto-card-container' key = {id}>

        <div className = 'produto-card-flex'>
            <img alt = {image} src = {require(`../../Assets/${image}`)}/>
         
        </div>
    </div>
}

export default Produto;

but in my page the image appear likes this enter image description here

i tried to console the path and the image name to see what's happened My console log of the const image

super-mario-odyssey.png
produto.js:8 call-of-duty-infinite-warfare.png
produto.js:8 the-witcher-iii-wild-hunt.png
produto.js:8 call-of-duty-wwii.png
produto.js:8 mortal-kombat-xl.png
produto.js:8 shards-of-darkness.png
produto.js:8 terra-media-sombras-de-mordor.png
produto.js:8 fifa-18.png
produto.js:8 horizon-zero-dawn.png

CodePudding user response:

Its necessary to indicate the type of image. In you case is .png

 <img alt = {image} src = {require(`../../Assets/${image}.png`)}/>

CodePudding user response:

Remember "require returns an object and image's path can be ejected from its default property".

So you must change the following code:

<img alt = {image} src = {require(`../../Assets/${image}`)}/>

To :

<img alt={image} src={require(`../../Assets/${image}.png`).default}/>

Note: If you want to use multi image formats, add imageFormat key to your json db and pass it's value as props.

{
    ...
    image: 'assassins-creed',
    imageFormat : 'jpg'
}

So if you do that, your code must be like to:

const {id, name, price, score, image, imageFormat} = data;

<img alt={image} src={require(`../../Assets/${image}.${imageFormat}`).default}/>

Good luck.

  • Related