In this guide, we’ll walk through how to consume a REST API in a React Native/Expo application. We’ll use a movie API to fetch data and display it in a list. For styling, we’ll use NativeWind, a utility-first CSS framework for React Native that makes styling simple and consistent.
Prerequisites
Before we begin, make sure you have the following installed:
- Node.js (v16 or higher)
- Expo CLI (npm install -g expo-cli)
- Basic knowledge of React Native and JavaScript
Step 1: Set Up a New Expo Project
First, let’s create a new Expo project:
npx create-expo-app@latest MovieApp
Choose the blank (TypeScript) or blank template when prompted. Once the project is created, navigate into the project folder:
cd MovieApp
Step 2: Install Required Dependencies
We’ll need a few libraries to make HTTP requests and style our app:
- Axios: A popular HTTP client for making API requests.
- NativeWind: A utility-first CSS framework for React Native.
Install the dependencies:
npm install axios nativewind
Next, install the required dependencies for NativeWind:
npm install tailwindcss postcss autoprefixer
Step 3: Configure NativeWind
To set up NativeWind, create a tailwind.config.js file in the root of your project:
npx tailwindcss init
Update the tailwind.config.js file to include the following:
module.exports = {
content: [
"./App.{js,jsx,ts,tsx}",
"./screens/**/*.{js,jsx,ts,tsx}",
"./components/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
};
Then, create a global.css file in the root of your project and add the following:
@tailwind base;
@tailwind components;
@tailwind utilities;
Finally, import the global.css file in your App.js:
import './global.css';
Step 4: Fetch Data from the Movie API
For this example, we’ll use the The Movie Database (TMDb) API. You’ll need to sign up and get an API key.
Once you have your API key, create a .env file in the root of your project to store it:
API_KEY=your_api_key_here
Install the expo-constants package to access environment variables:
npm install expo-constants
Update your babel.config.js to include the react-native-dotenv plugin:
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
plugins: [
['module:react-native-dotenv', {
moduleName: '@env',
path: '.env',
}],
],
};
};
Step 5: Create a Movie List Component
Create a new file components/MovieList.js and add the following code:
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, Image } from 'react-native';
import axios from 'axios';
import Constants from 'expo-constants';
const API_KEY = Constants.manifest.extra.API_KEY;
const MovieList = () => {
const [movies, setMovies] = useState([]);
useEffect(() => {
const fetchMovies = async () => {
try {
const response = await axios.get(
`https://api.themoviedb.org/3/movie/popular?api_key=${API_KEY}&language=en-US&page=1`
);
setMovies(response.data.results);
} catch (error) {
console.error(error);
}
};
fetchMovies();
}, []);
const renderItem = ({ item }) => (
<View className="p-4 border-b border-gray-200">
<Image
source={{ uri: `https://image.tmdb.org/t/p/w500${item.poster_path}` }}
className="w-full h-64 rounded-lg"
/>
<Text className="text-xl font-bold mt-2">{item.title}</Text>
<Text className="text-gray-600">{item.overview}</Text>
</View>
);
return (
<FlatList
data={movies}
renderItem={renderItem}
keyExtractor={(item) => item.id.toString()}
/>
);
};
export default MovieList;
Step 6: Update App.js
Now, update your App.js to include the MovieList component:
import React from 'react';
import { SafeAreaView } from 'react-native';
import MovieList from './components/MovieList';
export default function App() {
return (
<SafeAreaView className="flex-1 bg-white">
<MovieList />
</SafeAreaView>
);
}
Step 7: Run the App
Start your Expo development server:
expo start
Scan the QR code with the Expo Go app on your phone or run it on an emulator. You should see a list of popular movies fetched from the TMDb API, styled with NativeWind.
Conclusion
In this guide, we’ve learned how to:
- Set up a React Native/Expo project.
- Install and configure NativeWind for styling.
- Fetch data from a REST API using Axios.
- Display the data in a list with custom styles.
You can now extend this example by adding more features, such as search functionality, movie details, or pagination. Happy coding! 🚀