How to Call an API in React Native and Display Data in a Table Format
Table of Contents
Introduction
When building mobile applications, fetching data from a backend API and displaying it effectively is crucial. In this article, we will explore how to call an API in React Native, read data from the response, and format it in a table layout. Using practical examples, we’ll demonstrate the techniques needed to accomplish this with minimal dependencies. React Native makes it relatively easy to work with APIs and display data, making it a powerful tool for developers. This approach will work seamlessly on both Android and iOS, enabling you to deliver a consistent experience to your users. Let’s dive into the essentials!
Why Use a Table Layout in React Native?
Tables are an effective way to display organized data in a structured format. While HTML in web development has table elements like <table>
, <tr>
, and <td>
, these elements don’t exist in React Native since it’s not a web-based platform. However, with React Native components like FlatList, you can simulate a table layout for presenting data.
Prerequisites
To follow along, you’ll need:
- Basic knowledge of React Native.
- A basic setup of React Native (You can use
npx react-native init MyApp
to create a new project). - Access to an API that returns JSON data.
Step-by-Step Guide
Step 1: Setting Up the React Native Project
If you haven’t set up a project yet, use the following command:
npx react-native init UserTableApp
This command will initialize a new React Native project named UserTableApp. Navigate into your project directory:
cd UserTableApp
Next, open your project in a code editor like Visual Studio Code.
Step 2: Creating the UserTable Component
In your project directory, create a new file named UserTable.js under the components folder (you may need to create the folder if it doesn’t exist). This file will contain our main component to fetch data and display it.
// components/UserTable.js
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';
const UserTable = () => {
const [users, setUsers] = useState([]);
// Fetch data from the API
useEffect(() => {
const fetchUsers = async () => {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
setUsers(data);
} catch (error) {
console.error("Error fetching data:", error);
}
};
fetchUsers();
}, []);
// Render a table row for each user
const renderUser = ({ item }) => (
<View style={styles.row}>
<Text style={styles.cell}>{item.name}</Text>
<Text style={styles.cell}>{item.username}</Text>
</View>
);
return (
<View style={styles.container}>
{/* Header Row */}
<View style={styles.header}>
<Text style={styles.headerCell}>Name</Text>
<Text style={styles.headerCell}>Username</Text>
</View>
{/* List of Users */}
<FlatList
data={users}
renderItem={renderUser}
keyExtractor={(item) => item.id.toString()}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 16,
},
header: {
flexDirection: 'row',
borderBottomWidth: 2,
borderColor: '#ddd',
paddingBottom: 8,
marginBottom: 8,
},
headerCell: {
flex: 1,
fontWeight: 'bold',
fontSize: 16,
},
row: {
flexDirection: 'row',
paddingVertical: 8,
borderBottomWidth: 1,
borderColor: '#eee',
},
cell: {
flex: 1,
fontSize: 14,
},
});
export default UserTable;
Step 3: Understanding the Code
Let’s break down each section of the UserTable component:
- Import Statements: Essential components like
useEffect
anduseState
from React are imported alongsideView
,Text
,FlatList
, andStyleSheet
from React Native. - State Management: Using the
useState
hook, we create a state variable users to store data fetched from the API. - useEffect Hook: In the
useEffect
hook, we define a function fetchUsers that makes a call to an API endpoint and sets the fetched data to the users state. - Error Handling: A try-catch block inside fetchUsers ensures any API errors are logged.
- Table Layout:
- The header row includes static Text components labeled “Name” and “Username.”
- FlatList takes users as its data source, rendering each item with renderUser.
Step 4: Integrating the Component
Next, let’s integrate UserTable in the main App.js file to display the table layout in the app.
// App.js
import React from 'react';
import { SafeAreaView } from 'react-native';
import UserTable from './components/UserTable';
const App = () => {
return (
<SafeAreaView style={{ flex: 1 }}>
<UserTable />
</SafeAreaView>
);
};
export default App;
The SafeAreaView component ensures that your content stays within the safe area boundaries of a device. This helps prevent overlapping with any system UI elements, such as notches on iPhones.
Step 5: Running the Application
Now, run the app on a simulator or physical device to see the table layout:
npx react-native run-android
# or
npx react-native run-ios
Once the app loads, you’ll see the table format with name and username fields displayed in a list-like structure.
Explanation of Key Concepts
- Async and Await: The fetchUsers function uses async-await syntax for making API calls asynchronously, keeping the app responsive by preventing blocking.
- FlatList:
- The FlatList component is efficient for rendering lists of data, especially when dynamic.
- Each item (or row) is rendered using the renderUser function.
- Error Handling: Error handling using a try-catch block ensures that if the API call fails, the error is caught and logged without crashing the app.
- KeyExtractor: A unique key for each item is set using the id field from API data.
Customizing the Table Layout
To make the table more visually appealing, enhance the styles object by adding padding, margin, background color, or even alternating row colors. Here’s an example with added alternating colors for rows:
const renderUser = ({ item, index }) => (
<View style={[styles.row, index % 2 === 0 ? styles.evenRow : styles.oddRow]}>
<Text style={styles.cell}>{item.name}</Text>
<Text style={styles.cell}>{item.username}</Text>
</View>
);
const styles = StyleSheet.create({
// other styles...
evenRow: {
backgroundColor: '#f9f9f9',
},
oddRow: {
backgroundColor: '#ffffff',
},
});
With these changes, each row will have slightly different background colors, making it easier to distinguish individual rows.
Benefits and Use Cases
Creating an API call in React Native and displaying data in a structured format opens up numerous possibilities:
- E-commerce Apps: Displaying product information in structured tables.
- Employee Management Systems: Listing employee details like name and ID.
- Student Information Systems: Showing student names and grades.
Conclusion
Displaying data in a table format in React Native is both simple and effective. By using React Native’s FlatList component and some styling techniques, you can simulate a table layout for your data. This approach enhances organization and readability within your mobile application. In this article, we covered setting up an API call, fetching data, displaying it in a table layout, and styling each element for clarity. Experiment with different APIs and styling options to create unique layouts that enhance user experience! By mastering how to fetch data from APIs using async / await syntax and understanding how to effectively use FlatList for rendering lists of data in React Native applications, you can significantly improve your mobile app development skills.