トーストメッセージは、スナックバーと呼ばれることもあり、通知やメッセージを表示する一般的な方法です。例えば、ボタンを押したユーザーに、操作が正常に完了したことを伝える際に役立ちます。
公式ドキュメントには、次の例が掲載されています。
まず、プロジェクトのルートディレクトリで次のコマンドを実行してインストールします。
npm install react-native-toast-message
プロジェクトの最上位ページを構成する /app/_layout.tsx に、次の設定を追加します。
app/_layout.tsximport Toast from 'react-native-toast-message';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<View>
{children}
<Toast />
</View>
);
}
1.2. React Native CLI環境で設定する 🔗
プロジェクトの最上位ページを構成する app.tsx に、次の設定を追加します。
app.tsximport Toast from 'react-native-toast-message';
export function App( props: any ) {
return (
<>
{/* ... */}
<Toast />
</>
);
}
表示したいコンポーネントで、次のように設定します。
app/index.tsximport Toast from 'react-native-toast-message';
import { Button } from 'react-native'
export function Page() {
const showToast = () => {
Toast.show({
type: 'success',
text1: 'Hello',
text2: 'This is some something 👋'
});
}
return (
<Button
title='Show toast'
onPress={showToast}
/>
)
}
見た目を変更する場合は、トーストを宣言した
/app/_layout.tsx(Expo)または
app.tsx(React Native CLI)に、次の設定を追加します。
この例では、3種類のトーストを表示します。successとerrorは標準のトーストを変更して使い、tomatoToastは独自のトーストを使います。
app/_layout.tsximport Toast, { BaseToast, ErrorToast } from 'react-native-toast-message';
const toastConfig = { // config 변수 추가
success: (props) => (
<BaseToast
{...props}
style={{ borderLeftColor: 'pink' }}
contentContainerStyle={{ paddingHorizontal: 15 }}
text1Style={{
fontSize: 15,
fontWeight: '400'
}}
/>
),
error: (props) => (
<ErrorToast
{...props}
text1Style={{
fontSize: 17
}}
text2Style={{
fontSize: 15
}}
/>
),
tomatoToast: ({ text1, props }) => (
<View style={{ height: 60, width: '100%', backgroundColor: 'tomato' }}>
<Text>{text1}</Text>
<Text>{props.uuid}</Text>
</View>
)
}
export default function Page() {
return (
<View>
{children}
<Toast config={toastConfig} />
</View>
);
}
表示したいコンポーネントで、次のように設定します。
app/index.tsximport Toast from 'react-native-toast-message';
import { Button } from 'react-native'
export function Page() {
const showToast = () => {
Toast.show({
type: 'tomatoToast',
props: { uuid: 'uuid example' }
});
}
const showErrorToast = () => {
Toast.show({
type: 'error',
text1: 'Error',
text2: 'This is some something 👋'
});
}
return (
<Button
title='Show toast'
onPress={showToast}
/>
)
}
不要なモーダルや確認ダイアログを減らし、トーストメッセージで伝えると、ユーザーが作業を続けやすくなります。実装も手軽なので、筆者はトーストメッセージの利用をおすすめします。