Reader small image

You're reading from  React and React Native - Fifth Edition

Product typeBook
Published inApr 2024
Reading LevelBeginner
PublisherPackt
ISBN-139781805127307
Edition5th Edition
Languages
Tools
Right arrow
Authors (2):
Mikhail Sakhniuk
Mikhail Sakhniuk
author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk

Adam Boduch
Adam Boduch
author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch

View More author details
Right arrow

Rendering Item Lists

In this chapter, you’ll learn how to work with item lists. Lists are a common web application component. While it’s relatively straightforward to build lists using the <ul> and <li> elements, doing something similar on native mobile platforms is much more involved.

Thankfully, React Native provides an item list interface that hides all of the complexity. First, you’ll get a feel for how item lists work by walking through an example. Then, you’ll learn how to build controls that change the data displayed in lists. Lastly, you’ll see a couple of examples that fetch items from the network.

We’ll cover the following topics in this chapter:

  • Rendering data collections
  • Sorting and filtering lists
  • Fetching list data
  • Lazy list loading
  • Implementing pull to refresh

Technical requirements

You can find the code files for this chapter on GitHub at https://github.com/PacktPublishing/React-and-React-Native-5E/tree/main/Chapter20.

Rendering data collections

Lists are the most common way to display a lot of information: for example, you can display your friend list, messages, and news. Many apps contain lists with data collections, and React Native provides the tools to create these components.

Let’s start with an example. The React Native component you’ll use to render lists is FlatList, which works the same way on iOS and Android. List views accept a data property, which is an array of objects. These objects can have any properties you like, but they do require a key property. If you don’t have a key property, you can pass the keyExtractor prop to the Flatlist component and instruct what to use instead of key. The key property is similar to the requirement for rendering the <li> elements inside of a <ul> element. This helps the list to efficiently render when changes are made to list data.

Let’s implement a basic list now. Here’s the code to render a basic...

Sorting and filtering lists

Now that you have learned the basics of the FlatList components, including how to pass data, let’s add some controls to the list that you just implemented in the Rendering data collections section. The FlatList component can be rendered together with other components: for example, list controls. It helps you to manipulate the data source, which ultimately drives what’s rendered on the screen.

Before implementing list control components, it might be helpful to review the high-level structure of these components so that the code has more context. Here’s an illustration of the component structure that you’re going to implement:

Picture 2

Figure 20.2: The component structure

Here’s what each of these components is responsible for:

  • ListContainer: The overall container for the list; it follows the familiar React container pattern
  • List: A stateless component that passes the relevant pieces of state into...

Fetching list data

Commonly, you’ll fetch your list data from some API endpoint. In this section, you’ll learn about making API requests from React Native components. The good news is that the fetch() API is polyfilled by React Native, so the networking code in your mobile applications should look and feel a lot like it does in your web applications.

To start things off, let’s build a mock API for our list items using functions that return promises just like fetch() does:

const items = new Array(100).fill(null).map((v, i) => `Item ${i}`);
function filterAndSort(data: string[], text: string, asc: boolean) {
  return data
    .filter((i) => text.length === 0 || i.includes(text))
    .sort(
      asc
        ? (a, b) => (b > a ? -1 : a === b ? 0 : 1)
        : (a, b) => (a > b ? -1 : a === b ? 0 : 1)
    );
}
export function fetchItems(
  filter: string,
  asc: boolean
): Promise<{ json: () => Promise<{ items: string[] }> }>...

Lazy list loading

In this section, you’ll implement a different kind of list: one that scrolls infinitely. Sometimes, users don’t actually know what they’re looking for, so filtering or sorting isn’t going to help. Think about the Facebook news feed you see when you log in to your account; it’s the main feature of the application, and rarely are you looking for something specific. You need to see what’s going on by scrolling through the list.

To do this using a FlatList component, you need to be able to fetch more API data when the user scrolls to the end of the list. To get an idea of how this works, you need a lot of API data to work with, and generators are great at this. So, let’s modify the mock that you created in the Fetching list data section’s example so that it just keeps responding with new data:

function* genItems() {
  let cnt = 0;
  while (true) {
    yield `Item ${cnt++}`;
  }
}
let items = genItems();...

Implementing pull to refresh

The pull-to-refresh gesture is a common action on mobile devices. It allows users to refresh the content of a view without having to lift a finger from the screen or manually reopen the app, just by pulling it down to trigger a page refresh. Loren Brichter, the creator of Tweetie (later Twitter for iPhone) and Letterpress, introduced this gesture in 2009. This gesture has become so popular that Apple integrated it into its SDKs as UIRefreshControl.

To use pull to refresh in the FlatList app, we just need to pass a few props and handlers. Let’s take a look at our List component:

type Props = {
  data: { key: string; value: string }[];
  fetchItems: () => Promise<void>;
  refreshItems: () => Promise<void>;
  isRefreshing: boolean;
};
export default function List({
  data,
  fetchItems,
  refreshItems,
  isRefreshing,
}: Props) {
  return (
    <FlatList
      data={data}
      renderItem={({ item }) => <Text style...

Summary

In this chapter, you learned about the FlatList component in React Native. This component is general-purpose, as it doesn’t impose any specific look on the items that get rendered. Instead, the appearance of the list is up to you, leaving the FlatList component to help with efficiently rendering a data source. The FlatList component also provides a scrollable region for the items it renders.

You implemented an example that took advantage of section headers in list views. This is a good place to render static content such as list controls. You then learned about making network calls in React Native; it’s just like using fetch() in any other web application.

Finally, you implemented lazy lists that scroll infinitely by only loading new items after you’ve scrolled to the bottom of what’s already been rendered. Also, we added a feature to refresh that list by means of a pull gesture.

In the next chapter, you’ll learn how to show the...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
React and React Native - Fifth Edition
Published in: Apr 2024Publisher: PacktISBN-13: 9781805127307
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Authors (2)

author image
Mikhail Sakhniuk

Mikhail Sakhniuk is Software Engineer with high proficiency in JavaScript, React and React Native. He has more than 5 years of experience in developing web and mobile applications. He has worked for startups, fintech companies, and product companies with more than 20 million users. Currently, Mikhail is working at Miro as a Frontend Engineer. In addition, he owns and maintains a few open-source projects. He also shares his experience and knowledge through books and articles.
Read more about Mikhail Sakhniuk

author image
Adam Boduch

Adam Boduch has been involved in large-scale JavaScript development for nearly 15 years. Before moving to the frontend, he worked on several large-scale cloud computing products using Python and Linux. No stranger to complexity, Adam has practical experience with real-world software systems and the scaling challenges they pose.
Read more about Adam Boduch