Home > Software design >  Rendering an image from a json file in a react component
Rendering an image from a json file in a react component

Time:12-29

Everything is rendered perfectly except for the pictures, for some reason they are not displayed, what is the reason?

There is the following component:

import React from 'react';
import data from '../data/data.json';
import './Product.css';

function Product() {
        return (
            <div className='block'>
                {data.map((el) => {
                    return (
                        <div className='product' key={el.id}>
                            <img className='product__image' src={el.img}></img>
                            <h3 className='product__title'>{el.title}</h3>
                            <h3 className='product__price'>{el.price}</h3>
                            <button className='product__button'>В корзину</button>
                        </div>
                    )
                })}
            </div>
        )
}

export default Product;

json:

[
    {"id":1,"title":"Гитара Yamaha", "price":"6500", "img":"./img/guitar-yamaha.jpg"},
    {"id":2,"title":"Гитара Fender", "price":"7300", "img":"./img/guitar-fender.jpg"},
    {"id":3,"title":"Скрипка Yamaha", "price":"16000", "img":"./img/yamaha-violence.jpg"},
    {"id":4,"title":"Скрипка Cervini", "price":"4200", "img":"./img/violence-cervini.jpg"},
    {"id":5,"title":"Саксофон Yamaha", "price":"45000", "img":"./img/saxophone-yamaha.jpg"},
    {"id":6,"title":"Барабаны Yamaha", "price":"30000", "img":"./img/drums-yamaha.jpg"}
]

CodePudding user response:

If your images folder is in public folder, you can do this:

 <img src='/img/image.jpg' />

Remove the dot . in the json image path and try like this.

[
  {"id":1,"title":"Гитара Yamaha", "price":"6500", "img":"/img/guitar-yamaha.jpg"},
  {"id":2,"title":"Гитара Fender", "price":"7300", "img":"/img/guitar-fender.jpg"},
  {"id":3,"title":"Скрипка Yamaha", "price":"16000", "img":"/img/yamaha-violence.jpg"},
  {"id":4,"title":"Скрипка Cervini", "price":"4200", "img":"/img/violence-cervini.jpg"},
  {"id":5,"title":"Саксофон Yamaha", "price":"45000", "img":"/img/saxophone-yamaha.jpg"},
  {"id":6,"title":"Барабаны Yamaha", "price":"30000", "img":"/img/drums-yamaha.jpg"}
]
  • Related