React Native - Toast Message
앱 개발의 UI 요소 중 자주 이용되는 것으로 Toast Message가 있다. 어플에서 어떤 버튼을 클릭하거나 기능을 실행하면 완료 메세지가 화면 상단이나 하단에 뜨는 것을 본 적이 있을 것이다. 이 Toast Message는 사용자의 반응에 즉각적으로 피드백하여 사용자경험을 향상시켜주는 효과가 있다.
https://www.npmjs.com/package/react-native-toast-message
react-native-toast-message
Toast message component for React Native. Latest version: 2.2.1, last published: 5 months ago. Start using react-native-toast-message in your project by running `npm i react-native-toast-message`. There are 130 other projects in the npm registry using reac
www.npmjs.com
1. 설치
npm install react-native-toast-message
# or
yarn add react-native-toast-message
2. 사용
App.tsx에 Toast를 추가해준다.
// App.tsx
import './global.css';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import Navigation from 'navigation';
import {RecoilRoot} from 'recoil';
import Toast from 'react-native-toast-message';
const App = () => {
return (
<RecoilRoot>
<SafeAreaProvider>
<Navigation />
<Toast />
</SafeAreaProvider>
</RecoilRoot>
);
};
export default App;
본인은 기능을 따로 빼서 만들어뒀는데 아래처럼 간단하게 만들어봤다.
// toastMessage.ts
import Toast, {ToastType} from 'react-native-toast-message';
export const showBottomToast = (type: ToastType, text: string) => {
Toast.show({
type,
text1: text,
position: 'bottom',
visibilityTime: 2000,
});
};
- type : toast 유형(success, error, info) / 커스텀 유형도 가능
- text1 : 첫 번째 줄 텍스트
- text2 : 두 번째 줄 텍스트
- position : toast 위치
- visibilityTime : autoHide가 되기까지 걸리는 시간(autoHide가 true인 경우에만)
- autoHide : 설정한 시간 이후에 자동으로 숨겨짐(default : true)
이 외에도 옵션이 몇 개 더 있지만 가장 많이 사용되는 옵션만 정리했다.
위처럼 추가하고 기능까지 만들어뒀다면 아래와 같이 간단하게 실행해주면 된다.
import CustomText from '@/components/text';
import {TestProps} from '@/types/stack';
import {showBottomToast} from '@/utils/toastMessage';
import {Button, View} from 'react-native';
import {SafeAreaView} from 'react-native-safe-area-context';
const TestScreen = ({navigation}: TestProps) => {
return (
<SafeAreaView className="flex-1">
<View className="w-full h-full flex justify-center items-center bg-white">
<CustomText className="text-success text-xl" children="테스트 화면" />
<Button
title="메세지"
onPress={() => {
showBottomToast('success', '성공입니다.');
}}
/>
</View>
</SafeAreaView>
);
};
export default TestScreen;
3. 실행
아래와 같이 잘 실행되는 것을 확인할 수 있다.
4. 커스텀 디자인 (config)
기능적으로는 간단하게 구현했지만, 디자인은 아무래도 아쉬워 커스텀 디자인이 필요한 경우가 있다.
그럴 때는 아래와 같이 config 파일을 생성하고 Toast의 config를 연결해주면 된다.
아래는 예시를 위해 만든 파일로 아이콘도 success, error, info 다 동일하게 되어있지만, 실제 사용하는 경우에는 당연히 본인 취향에 맞게 변경하면 된다.
// toast.config.tsx
import {
SuccessToast,
ErrorToast,
InfoToast,
ToastProps,
} from 'react-native-toast-message';
import {StyleSheet, Text, View} from 'react-native';
import CheckCircleOutline from '@assets/svg/check-circle-outline.svg';
export const toastConfig = {
success: (props: ToastProps) => (
<SuccessToast
{...props}
style={toastStyle.successToast}
contentContainerStyle={toastStyle.toastContent}
text1Style={toastStyle.toastText1}
renderLeadingIcon={() => <CheckCircleOutline color="#ffffff" />}
/>
),
error: (props: ToastProps) => (
<ErrorToast
{...props}
style={toastStyle.errorToast}
contentContainerStyle={toastStyle.toastContent}
text1Style={toastStyle.toastText1}
renderLeadingIcon={() => <CheckCircleOutline color="#ffffff" />}
/>
),
info: (props: ToastProps) => (
<InfoToast
{...props}
style={toastStyle.infoToast}
contentContainerStyle={toastStyle.toastContent}
text1Style={toastStyle.toastText1}
renderLeadingIcon={() => <CheckCircleOutline color="#ffffff" />}
/>
),
};
const toastStyle = StyleSheet.create({
successToast: {
backgroundColor: '#22bb33',
borderLeftColor: '#22bb33',
display: 'flex',
alignItems: 'center',
paddingLeft: 10,
},
errorToast: {
backgroundColor: '#FF2424',
borderLeftColor: '#FF2424',
display: 'flex',
alignItems: 'center',
paddingLeft: 10,
},
infoToast: {
backgroundColor: '#5bc0de',
borderLeftColor: '#5bc0de',
display: 'flex',
alignItems: 'center',
paddingLeft: 10,
},
toastContent: {
paddingHorizontal: 5,
},
toastText1: {
color: '#ffffff',
},
});
이 후, App.tsx에 추가했던 toast 컴포넌트의 config를 연결해주면 된다.
// App.tsx
import './global.css';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import Navigation from 'navigation';
import {RecoilRoot} from 'recoil';
import Toast from 'react-native-toast-message';
import {toastConfig} from '@/config/toast.config';
const App = () => {
return (
<RecoilRoot>
<SafeAreaProvider>
<Navigation />
<Toast config={toastConfig} />
</SafeAreaProvider>
</RecoilRoot>
);
};
export default App;
5. 실행
아래와 같이 변경한 커스텀 디자인이 잘 적용된 것을 확인할 수 있다.