乐闻世界logo
搜索文章和话题

How to display toast message in react native

1个答案

1

When developing applications with React Native, displaying toast messages is a common requirement. In React Native, there are several different methods to achieve this functionality.

Method One: Using the Built-in ToastAndroid Component (Android Only)

The React Native framework provides an internal component ToastAndroid for the Android platform, which can be used to display brief toast messages. Using this component is straightforward, as shown below:

jsx
import { ToastAndroid } from 'react-native'; // Display Toast message ToastAndroid.show('This is a Toast message', ToastAndroid.SHORT);

Here, ToastAndroid.SHORT and ToastAndroid.LONG define different display durations.

Method Two: Using a Third-Party Library (Cross-Platform)

Since ToastAndroid is only available on the Android platform, if you need to achieve the same functionality on iOS, you will need to use a third-party library. A popular choice is react-native-toast-message.

First, add the third-party library to your project:

sh
npm install react-native-toast-message

Then, import and set up Toast in the App component:

jsx
import Toast from 'react-native-toast-message'; // Use Toast component Toast.show({ type: 'success', position: 'bottom', text1: 'Hello World!', text2: 'This is a Toast message.' }); // Ensure that the Toast component is rendered in the root component of the application export default function App() { return ( <> {/* Other components */} <Toast ref={(ref) => Toast.setRef(ref)} /> </> ); }

The react-native-toast-message library provides more configuration options and customization features, making it easier to implement toast messages in your application.

Practical Application Example

In an e-commerce application I've developed, we needed to display a toast message when a user adds an item to the shopping cart. We implemented this functionality using the react-native-toast-message library. Whenever the user clicks the add button, we call the Toast.show method to confirm that the item has been added. This improves the user experience by providing immediate feedback.

jsx
// Add product to cart addProductToCart(product) { // ... add product logic Toast.show({ type: 'success', position: 'bottom', text1: 'Added successfully!', text2: `${product.name} has been added to the shopping cart.` }); }

This way, regardless of the platform the user is using, they receive a consistent user experience.

2024年6月29日 12:07 回复

你的答案