0
votes

How do i fix a local path from Json to my React components rendering,

I searched for answer all over the internet, but NO luck :(

NOT WORKING :(
[
    {
        "name": "Apple",
        "id": "001",
        "price": "$995",
        "imgUrl": "./Pictures/219.jpg"
    }
]

WORKING, BUT TURTLE SPEED :/
[
    {
        "name": "Apple",
        "id": "001",
        "price": "$995",
        "imgUrl": "http://www.placekitten.com/200/200"
    }
]

import React from 'react' class Product extends React.Component { constructor(props) { super(props) }

render() {
    return (
        <div>
            <img src={this.props.imgUrl}> />
            <p>Name: {this.props.name}</p>
            <p>Id: {this.props.id}</p>
            <p>Price: {this.props.price}</p>
        </div >
    )
}

}


1

1 Answers

0
votes

Since I'm not sure if you're using Webpack to serve your Images. I'm going with the assumption that you're not and here's basic way to serve images from you're public directory.

here's structure:

public
|-assets
    |-pictures
       |-219.jpg
|-src
    |-myImgs.json
    |-App.js

json file:

  {
        "name": "Apple",
        "id": "001",
        "price": "$995",
        "imgUrl": "./pictures/219.jpg"
  }

App.js

import React from 'react';
import myImgs from './myImgs.json'

class App extends React.Component {
...
render() {
  return(
   <>
     <img src={myImgs.imgUrl} alt={myImgs.name} />
   </>
  )
 };
...
};