0

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 Answer 1

0

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} />
   </>
  )
 };
...
};

Sign up to request clarification or add additional context in comments.

3 Comments

I am using webpack to host the server. But i want to put all my image in a folder Images. Then i want the path in json file to link to the image folder.
I also have a component Search with the following to render every single data I store in json file: const product = this.state.Data.filter(search(this.state.search)).map(data => <Product name={data.name} id={data.id} price={data.price} imgUrl={data.imgUrl} />)
That should still work, but webpack won't be serving the images if you have them in your public dir.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.