How to Render Data from an API in your React App

Carl-Brain Egebe
3 min readJul 13, 2021

I’m going to use a 2 item store consisting of milk and broccoli to demonstrate the layout in React.

Start off by including the following at the top of your React component:

Import React, { useState} from “react”;

Import { v4 as uuid } from “uuid;

Next, create the react function with sample data included(could be fetched or hard-coded like I’m going to do).

the shop items

The sample data has to be mapped over to create actual store items out of its data. With that, an Item component will have to be created so with the object data of each element in the sample data, a store item would be created. This is done by passing the needed object data as props to the Item component.

Notice, one of the props is a key. In react, a key is required. This is so that React can identify which items have changed, are added, or are removed(avoid using index as key for it can cause issues when items are deleted). “displayItems” is now an array of Item components.

Now, In the Item component, we want to use the props passed down to create the template for each store item. Here, I use just the item name and quantity. Other things can be included such as images, price, etc.

The optionDropdown function is important here as it dynamically renders the amount available to add to cart. Without it, it’ll be difficult to accurately create an option dropdown for items with different quantities. Here’s a breakdown of what optionDropdown is doing:

An empty options array is created. Next, a for loop is created which pushes a number into the options array during each iteration, starting at 1. Once there is a number for each quantity in the options array, map over it and create an option tag for each value. So if the quantity was 15, there will be 15 option tags created. Finally, embed this list of option tags within a select tag.

With a little bit of styling, here’s what your application should look like

--

--