To set up our json data in our application: Create a new file in the applications ‘public’ folder called db.json. In this file you can code a JSON object named with a key of your preference (my example: “products”) that includes an array value of all of the items that you’d liked to specify as your data.
Again, you can either host your images on a 3rd party site and incorporate another key value pair per each item here (ex: url: “http://……), or like in my example, you will create a new folder named ‘products’ and save all of your corresponding images into this folder. To follow along, please name each image by their sku + “_2” + “.jpg”. Next, run: “npm install -g json-server”. This will install our json-server for a mock REST API. We’ll need to get this mock server running before we make our fetch request, run command: “json-server public/db.json — port 8000”.
We are now ready to fetch this data and connect our images.
Upon the components mounting, we want our program to immediately make our first fetch to our data and render all products to the DOM. For the sake of this example we will code all of this initial fetch and render our Products component in our App.js file. We will immediately store the data from our fetch in our local state object (as products) and then send that info as a prop to our Products container.
Our Products component will be responsible for mapping over the products prop that it receives and rendering the data according to how you want it to appear on the DOM. You’ll notice that on line 9 in Products.js image below, the image src is called using the product.sku key.
Please find an example of this working mock API server in my github repo: https://github.com/osha7/ecommerce-with-filter. Happy Coding!