How to create ActivityIndicator in React Native
In React Native, the ActivityIndicator component displays a circular loading indicator when there is a delay in action-response times. Some mobile applications have a delayed response to user actions, so developers need to show the real-time status of the specific event to prevent users from perceiving the application as unresponsive or malfunctioning. This is where the significance of showing loading spinners comes into play.
The ActivityIndicator component in React Native has several props that can be used to customize its behavior and appearance. Here are some commonly used props:
animating(boolean): Specifies whether theActivityIndicatorshould animate or not.color(string): Sets the color of the activity indicator.size(string or number): Specifies the size of the activity indicator. It can be one of "small", "large" or a numeric value representing the size in pixels.hidesWhenStopped(boolean): Determines whether the activity indicator should be hidden when not animating.
Boiler code for ActivityIndicator
We will start by creating a basic code for an ActivityIndicator, which shows a loading screen.
import React from 'react';import {ActivityIndicator, StyleSheet, View} from 'react-native';const App = () => (<View style={[styles.container, styles.horizontal]}><ActivityIndicator /><ActivityIndicator size="large" /><ActivityIndicator size="small" color="#0000ff" /><ActivityIndicator size="large" color="#00ff00" /></View>);const styles = StyleSheet.create({container: {flex: 1,justifyContent: 'center',backgroundColor: 'lightgrey',},horizontal: {flexDirection: 'row',justifyContent: 'space-around',padding: 10,},});export default App;
Lines 1–2: The code imports the necessary modules, such as
Reactand components likeActivityIndicatorandView, from the 'react' and 'react-native' libraries.Lines 4–11: The
Appcomponent is a functional component that renders aViewcontaining multiple instances of theActivityIndicatorcomponent with different configurations. They are rendered with different props, such assizeandcolor, to customize their appearance.
The provided code will display a screen with different sizes and colors of loading indicators. We can see the actual functionality and applications of the ActivityIndicator component in React Native development in the subsequent example.
ActivityIndicator in React Native application
Now we will see a use case for implementing a loading mechanism. We will fetch data from an API, accounting for potential delays, and display a loading sign until the data is retrieved. This ensures a smoother and more user-friendly experience, preventing any potential errors while fetching data.
In this simple example, we will simulate a two second delay before rendering a list. This simulates the behavior of fetching data from an API and waiting for the Promise to be resolved before displaying the data.
async function fetchItems() {await new Promise((resolve) => setTimeout(resolve, 2000));return ['Weclcome','To','Educative', 'ReactNative','ActivityIndicator'];}function Item({ name }) {return (<View style={styles.item}><Text style={styles.itemText}>{name}</Text></View>);}function App() {const [items, setItems] = useState([]);const [loading, setLoading] = useState(true);useEffect(() => {fetchItems().then((items) => {setItems(items);setLoading(false);});}, []);const renderItem = ({ item }) => (<Item name={item}/>);return (<SafeAreaView style={styles.container}>{ loading ?<ActivityIndicator size={90} color="#00ff00" />:<FlatListdata={items}renderItem={renderItem}/> }</SafeAreaView>);};
Lines 1–4: The
fetchItemsfunction is an asynchronous function that returns a Promise, simulating a 2-second delay usingsetTimeout, and then returns an array of strings representing the items.Lines 5–11: The
Itemcomponent is a functional component that takes anameprop and renders aViewwith a text displaying thename.Lines 12–20: The
Appcomponent is a functional component that uses theuseStatehook to manage the state ofitems(initially an empty array) andloading(initially set to true). TheuseEffecthook is used to fetch theitemswhen the component changes and update the state accordingly.Lines 22–24: The
renderItemfunction is used by theFlatListcomponent to render each item from theitemsarray. It returns theItemcomponent with thenameprop set to the current item.Lines 25–35: The return statement in the
Appcomponent renders the UI, showing anActivityIndicatorwhenloadingis true. Otherwise, it renders aFlatList.
Here is a complete React Native application showcasing a loading mechanism using ActivityIndicator to display a loading screen and a list of items once the loading is complete.
import React, { useState, useEffect } from 'react';
import {
SafeAreaView,
FlatList,
ActivityIndicator,
StyleSheet,
Text,
View,
} from 'react-native';
async function fetchItems() {
await new Promise((resolve) => setTimeout(resolve, 2000));
return ['Weclcome','To','Educative', 'ReactNative','ActivityIndicator'];
}
function Item({ name }) {
return (
<View style={styles.item}>
<Text style={styles.itemText}>{name}</Text>
</View>
);
}
function App() {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchItems().then((items) => {
setItems(items);
setLoading(false);
});
}, []);
const renderItem = ({ item }) => (
<Item name={item}/>
);
return (
<SafeAreaView style={styles.container}>
{ loading ?
<ActivityIndicator size={90} color="#00ff00" />:
<FlatList
data={items}
renderItem={renderItem}
/> }
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
item: {
backgroundColor: '#000080',
padding: 12,
marginBottom: 12
},
itemText: {
color: '#fff',
fontSize: 24,
}
});
export default App;Conclusion
The ReactNative ActivityIndicator is a useful component for displaying loading animations in apps. It can be customized to match the app's design and provides a visual to indicate ongoing processes or waiting for data. Using this component, developers can enhance the user experience and make their apps more engaging. Whether it's a simple spinner or a more complex animation, the ActivityIndicator serves its purpose effectively.
Free Resources