PromleeBlog
sitemapaboutMe

posting thumbnail
React Native에서 화면 새로고침하기 (refreshControl)
Refresh the screen in React Native (refreshControl)

📅

🚀

들어가기 전에🔗

이 포스트는 Expo 환경에서 작성되어 있지만 모든 React Native 환경에서 적용되는 내용입니다.
또한, 기본적인 셋팅이 되어있는 프로젝트를 기준으로 작성되었습니다.

새로고침 기능을 구현하는 이유🔗

앱에서는 보통 바텀 탭 메뉴가 있어 페이지 간 이동을 수월하게 해주는 장점이 있습니다. 하지만 다른 탭에서 사용자가 데이터를 수정하고 나서 다른 탭으로 돌아오면 첫 로딩된 데이터를 고정적으로 보여주고, 수정된 데이터를 다시 반영하지 않습니다. 이런 경우 새로고침 기능을 구현해야 합니다.

🚀

1. ScrollView 컴포넌트 만들기🔗

제일 먼저, 새로고침 기능을 구현할 화면을 만들어야 합니다. 우리가 사용할 refreshControl 컴포넌트는 ScrollView 컴포넌트 내부에서 사용됩니다. 가상의 데이터와 함께 목록을 보여주는 화면을 만들어보겠습니다.
/app/index.tsx
import React, { useState } from 'react';
import { Text, ScrollView } from 'react-native';
 
const List = () => {
  const [refreshTime, setRefreshTime] = useState(0);
 
  return (
    <ScrollView style={{ flex: 1, backgroundColor: 'white', padding: 20 }}>
      {Array.from({ length: 100 }).map((_, index) => (
        <Text key={index} style={{ textAlign: 'center', justifyContent: 'center', fontSize: 30 }}>
          {`새로고침 ${refreshTime}회`}
        </Text>
      ))}
    </ScrollView>
  );
};
 
export default List;
ScrollView 컴포넌트 예시
ScrollView 컴포넌트 예시

🚀

2. 새로고침 기능 구현하기🔗

이제 ScrollView 컴포넌트의 내부 속성인 refreshControl을 사용하여 새로고침 기능을 구현해보겠습니다.
RefreshControl 컴포넌트는 스크롤뷰 또는 목록뷰 내부에서 풀 투 새로고침 기능을 추가하는 데 사용됩니다. 스크롤뷰가 scrollY: 0에 있을 때 아래로 스와이프하면 onRefresh 이벤트가 트리거됩니다. refreshing 속성은 새로고침 상태를 나타내며, onRefresh 이벤트는 새로고침 기능을 구현하는 함수입니다. 시각적으로 동작을 확인하기 위해 1초의 딜레이를 주었습니다.
/app/index.tsx
import React, { useState } from 'react';
import { Text, ScrollView, RefreshControl } from 'react-native';
 
const List = () => {
  const [refreshing, setRefreshing] = useState(false); // 새로고침 상태를 나타내는 상태 변수
  const [refreshTime, setRefreshTime] = useState(0);
 
  const handleRefresh = () => { // 새로고침 기능을 구현하는 함수
    setRefreshing(true);
    setTimeout(() => { // 1초의 딜레이
      setRefreshTime(refreshTime + 1); // 새로고침시 실행되는 함수
      setRefreshing(false);
    }, 1000);
  };
 
  return (
    <ScrollView
      style={{ flex: 1, backgroundColor: 'white', padding: 20 }}
      refreshControl={<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />}
    >
      {Array.from({ length: 100 }).map((_, index) => (
        <Text key={index} style={{ textAlign: 'center', justifyContent: 'center', fontSize: 30 }}>
          {`새로고침 ${refreshTime}회`}
        </Text>
      ))}
    </ScrollView>
  );
};
 
export default List;
새로고침 기능 테스트
새로고침 기능 테스트

🚀

3. 기타 추가 속성🔗

RefreshControl의 Props는 기본적으로 View 컴포넌트의 Props를 상속받습니다. 그 이외에 아래와 같은 속성을 사용할 수 있습니다.

3.1. colors / tintColor🔗

colors 속성은 Android에서만 사용되며 tintColor 속성은 iOS에서만 사용됩니다. 두 속성은 새로고침 아이콘의 색상을 설정합니다. colors 속성은 리스트 형태이며 아이콘이 나타나 있는 동안 indicator 색상이 차례로 변경됩니다.
colors 속성 예시
/app/index.tsx
// ... 
	<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} colors={['blue', 'red', 'green']} /> // Android
	<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} tintColor="blue" /> // iOS
// ...

3.2. enabled (Android)🔗

새로고침 기능을 활성화/비활성화합니다. 기본값은 true입니다.
/app/index.tsx
// ... 
	<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} enabled={false} /> 
	// 새로고침 기능 비활성화 (Android)
// ...

3.3. progressBackgroundColor (Android)🔗

새로고침 아이콘의 배경색을 설정합니다. colors와 다르게 하나의 색상만 설정할 수 있습니다.
/app/index.tsx
// ... 
	<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} progressBackgroundColor="blue" />
	// 새로고침 아이콘의 배경색 설정 (Android)
// ...

3.4. size (Android)🔗

새로고침 아이콘의 사이즈를 설정합니다. 기본값은 'default'이며 'large'를 설정하면 더 큰 아이콘으로 보입니다.
/app/index.tsx
// ... 
	<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} size="large" />
	// 새로고침 아이콘의 사이즈 설정 (Android)
// ...

3.5. title, titleColor (Ios)🔗

새로 고침 아이콘 아래에 제목이 표시됩니다. titleColor 속성은 제목의 색상을 설정합니다.
/app/index.tsx
// ... 
	<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} title="새로고침" titleColor="blue" />
	// 새로고침 아이콘 아래에 제목 표시 (Ios)
// ...

🚀

결론🔗

서버의 데이터를 자동으로 Fetching 하는 것에 한계가 있다면 사용자가 직접 새로고침을 할 수 있도록 해야 합니다. 특히 앱에서 이런 기능을 필요한 곳에 적용하면 사용자 경험을 향상시킬 수 있습니다.

더 생각해 보기🔗

참고🔗