ActivityIndicator là component tích hợp sẵn của React Native để hiển thị vòng quay tải (spinner) khi ứng dụng đang xử lý tác vụ mất thời gian (gọi API, tải dữ liệu, v.v.).
Import
import { ActivityIndicator, View, StyleSheet } from 'react-native';
Cú pháp cơ bản
<ActivityIndicator
animating={true}
color="#bc2b78"
size="large"
style={styles.indicator}
/>
Các props chính
| Prop | Kiểu | Mô tả |
|---|---|---|
animating | boolean | true: hiển thị & quay, false: ẩn & dừng. |
color | string | Màu của spinner. |
size | enum | 'small' (20px) hoặc 'large' (36px - mặc định). |
hidesWhenStopped | boolean | Tự ẩn khi animating={false} (mặc định: true). |
Ví dụ cơ bản: Tự ẩn sau 60 giây
import React, { Component } from 'react';
import { ActivityIndicator, View, StyleSheet } from 'react-native';
class ActivityIndicatorExample extends Component {
state = { animating: true };
closeActivityIndicator = () =>
setTimeout(() => this.setState({ animating: false }), 60000);
componentDidMount = () => this.closeActivityIndicator();
render() {
const { animating } = this.state;
return (
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
marginTop: 70,
},
activityIndicator: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
height: 80,
},
});
export default ActivityIndicatorExample;
Ví dụ thực tế: Loading khi fetch API
import React, { useState, useEffect } from 'react';
import { ActivityIndicator, View, Text, StyleSheet } from 'react-native';
const DataFetching = () => {
const [loading, setLoading] = useState(true);
const [data, setData] = useState(null);
const [error, setError] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(res => res.json())
.then(json => {
setData(json);
setLoading(false);
})
.catch(err => {
setError(err.message);
setLoading(false);
});
}, []);
if (loading) {
return (
Đang tải dữ liệu...
);
}
if (error) return Lỗi: {error} ;
return (
{data.title}
{data.body}
);
};
const styles = StyleSheet.create({
centered: { flex: 1, justifyContent: 'center', alignItems: 'center' },
loadingText: { marginTop: 10, fontSize: 16 },
container: { flex: 1, padding: 20 },
title: { fontSize: 20, fontWeight: 'bold', marginBottom: 10 },
error: { color: 'red', textAlign: 'center', marginTop: 20 },
});
export default DataFetching;
Mẹo hay
- Bọc
ActivityIndicatortrongViewcóflex: 1vàjustifyContent: 'center'để căn giữa màn hình. - Dùng
react-native-papernếu muốnProgressBarhoặcSnackbarloading đẹp hơn. - Trên Android,
colormặc định là xám, nên chỉ định rõ màu thương hiệu.