React basic 7 — Render a List from the API response

In the previous post (React basic 6 — Use Axios Library to Fetch Data), we've got image data from the Unsplash API and stored it in the React state. This post covers the basic steps to render the response in a list, such as creating an array of JSX elements from the data array.

Creating a simple list component with map function to render those images

Map in javascript allows you to alter elements of an array and create a brand new array of these altered elements retaining the original order. As shown in the below diagram, the same operation can be done using a for loop, but Map allows you to keep this operation simple and clean.

Below example code shows the real application to the image list code from the previous post. For rendering img elements, a new ImageItem component was added to this app. Map operation takes the original array of image data, and creates a new array of ImageItem components mapped with image data.



Place unique key values to each list item

In order to maximize its performance, React tries to avoid rendering already-rendered components again. Although it's not a requirement, adding a unique key value to each list element is highly recommended in creating a list in React. The key value should be added to the most parent element of each list item, ImageItem component in this case from the example below.

Access DOM with React Refs

In order to render elements neatly, we sometimes need to access rendered DOM elements and change their settings. For instance, when you create a grid layout with dynamic sized images, you want to access the clientHeight value of each image after it gets rendered.

Refs can be a solution to do so, though it is not recommended to overuse them. As shown in the example below, you will need to initialize a Ref by React.createRef() in constructor(), and add an attribute ref= { } to a JSX element to reference. In componentDidMount() lifecycle, DOM elements are accessible through this Ref.

The final project

Table of content

React basic 1 — “Hello React World”. Setting Up Your First React App

React basic 2 — JSX, the syntax extension to JavaScript that looks like HTML

React basic 3 — Reusable Functional Components

React basic 4 — Class Based Component and Lifecycle Methods

React basic 5 — Basic Event Handlers

React basic 6 — Use Axios Library to Fetch Data

React basic 7 — Render a List based on the API response

React basic 8 — Build React App and Host it on Server


Modern React with Redux by Stephen Grider | Udemy

Map | MDN Web Docs

Refs and the DOM | React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store