React Native Tutorial
- React Native Tutorial
- React Native Environment Setups
- React Native First Application Hello World
- React Native View
- React Native State
- React Native Props
- React Native Style
- React Native Height and Width
- React Native Button
- React Native Layout and Flexbox
- React Native Positioning Element with Flex
- React Native ScrollView
- React Native ListView
- React Native FlatList
- React Native SectionList
- React Native Touchables
- React Native Text Input
- React Native ActivityIndicator
- React Native Picker
- React Native StatusBar
- React Native Switch
- React Native WebView
- React Native ProgressBarAndroid
- React Native ProgressBar With Animated
Navigation
- React Native Navigation
- React Native Configuring Header Bar
- React Native Moving Between Screens
- React Native Passing Value between Screen
- React Native Tab Navigation
- React Native Adding Icons at the Bottom of Tab Navigation
- React Native Create Material Bottom Tab Navigator
- React Native Top Tab Navigator
- React Native Drawer Navigation
Storage
React Misc
- React Native Google Map
- React Native Modal
- React Native Vector Icons
- React Native Splash Screen
- React Native vs. Ionic
- React Native vs. Xamarin
- React Native vs Flutter
- React Native vs React
- React Native vs Swift
- Box shadow in React Native
- React Native IAP
- React-Native Localization
- React Native Toast
- React Native Sound
React Native Toast
What is a Toast?
Toasts are the technique in mobile development to notify the users about interrupting what they're doing.
According to the Android Developer Documentation: "A toast provides the feedback of the operation in a small pop-up window. It fills the space required for the message, and the activity is visible and interactive. Toasts automatically disappear afterward." of a waiting time".
React Native's Toast Android API exposes the Android platform's ToastAndroid module in the JS module.
It provides the thing (message, duration) method, which takes the below parameters:
- Message: It is a string with the text to toast
- Duration: The duration of Toast is either the
ToastAndroid.SHORT or ToastAndroid.LONG.
Alternatively, we can use the display with severity (message, duration, severity) to specify where the TToastappears on the screen layout. Maybe the ToastAndroid.TOP, ToastAndroid.BOTTOM, or ToastAndroid.CENTER.
The 'showWithGravityAndOffset(message, duration, gravity, xOffset, yOffset)' adds the ability that specify an offset in the pixels.
import { View, StyleSheet, ToastAndroid, Button, StatusBar } from "react-native";
Application constant = () => {
const displaytoast = () => {
ToastAndroid. Show("A Pikachu appeared nearby!", ToastAndroid.SHORT);
};
const displayToastGravity = () => {
ToastAndroid.showWithGravity(
"All the things belong to us",
ToastAndroid.SHORT,
ToastAndroid.CENTER
);
};
const displayToastWithGravityAndOffset = () => {
ToastAndroid.showWithGravityAndOffset(
"A wild toast appeared!",
ToastAndroid.LONG,
ToastAndroid.BOTTOM,
25,
fifty
);
};
return (
<View style={styles.container}>
<Button title="Toggle Toast" onPress={() => showToast()} />
<Button
title="Toggle toast with gravity"
onPress={() => displayToastWithGravity()}
/>
<Button
title="Toggle toast with gravity and offset"
onPress={() => displayToastWithGravityAndOffset()}
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
bending: 1,
justifyContent: "center",
paddingTop: StatusBar.currentHeight,
backgroundcolor: "#888888",
padding: 8
}
});
export app;
Imperative hack
The ToastAndroid API is a must, but there is a way to expose a declarative component like in this example:
import { View, StyleSheet, ToastAndroid, Button, StatusBar } from "react-native";
const Toast = ({ visible, message }) => {
if (visible) {
ToastAndroid.showWithGravityAndOffset(
message,
ToastAndroid.LONG,
ToastAndroid.BOTTOM,
25,
fifty
); return null;
}
return null;
};
Application constant = () => {
const [visibleToast, setvisibleToast] = useState(false);
useEffect(() => setvisibleToast(false), [visibleToast]);
const handleButtonPress = () => {
setvisibleToast(true);
};
return (
<View style={styles.container}>
<Toast visible={visible Toast} message="Example" />
<Button title="Toggle Toast" onPress={() => handleButtonPress()} />
</View> );
};
const styles = StyleSheet.create({
container: {
bending: 1,
justifyContent: "center",
paddingTop: StatusBar.currentHeight,
backgroundcolor: "#888888",
padding: 8
}
});
export the default application;
Methods
- show()
- staticshow(message, duration)
- showGravity()
- static show with gravity (message, duration, gravity)
- displayWithGravityAndOffset()
- static show with gravity and offset (message, duration, gravity, x-offset, y-offset)
Properties
SHORT
It indicates the duration on the screen.
LENGTH
It indicates the duration of the screen.
UP
It indicates the position of the screen.
DOWN
It indicates the position of the screen.
CENTER
It indicates the position of the screen.
How to display a toast popuppopup?
We have two solutions: an API from the react-native package and a library maintained by the React Native community to present a toast.
Android only: ToastAndroid
Toasts are a native Android feature, but iOS doesn't have them by default. If we need Toaston Android, we can use the ToastAndroid API provided by React Native.
Uses
Import ToastAndroid from the 'react-native' package and call ToastAndroid.show with a message and duration option to display a toast with the help of ToastAndroid:
import { View, StyleSheet, ToastAndroid, Button, StatusBar } from 'react-native';
export default function App() {
showtoast() function {
ToastAndroid.show('Request sent successfully!', ToastAndroid.SHORT);
}
return (
<View style={styles.container}>
<Button title="Show toast" onPress={show toast} />
</View>
);
}
const styles = StyleSheet.create({
container: {
bending: 1,
justifyContent: 'center',
paddingTop: StatusBar.currentHeight,
backgroundcolor: '#6638f0',
padding: 8,
},
});
The upper code results in the on a Pixel below:
There are many other ways to set the toast position, duration, and severity options.
Cross-platform: react-native-root-toast
Uses
To use react-native-root-toast, you should install the module from npm with npm install react-native-root-toast.
Then we need to wrap the root component of the app with to allow the sibling in your app.
// in your render function
return (
<RootSiblingParent> // <- use RootSiblingParent to wrap your root component
<Request />
</RootSiblingParent>
);
Then anywhere in the app, import Toast from react-native-root-toast and call Toastshow and Toasthide to manage the Toast on the screen.
let toast = Toast.show('Request failed to send.', {
duration: Toast.durations.LONG,
});
// hide the Toast, or it disappear after a timeout of `duration` ms.
setTimeout(function hideToast() {
Toast.hide(toast);
}, 500);
React-native-root-toast also has a component API if you want to manage the toasts declaratively.
An animated toast message component for React Native
An animated toast message component used for React Native to be called imperatively.
Install
Use
// Add the root component of your app
import Toast from 'react-native-toast-message?
constant root = () =>}
return (
<Toast ref={(ref) => Toast.setRef(ref)} />)
}
export default root
Then use it in the app:
Toast.show({
text1: 'Hello’,
text2: 'This is something ðŸ'‹'
})
api
show(options ={}}
We can use the following options to suit the needs. Everything is optional unless specified when calling the show method.
The use of | below is that one of the displayed values be used. If only one value is displayed, then it is the default value.
type: 'success | mistake | information',
position: 'top | down',
text1: 'Hello?,
text2: 'This is something ðŸ'‹?,
visibility time: 4000,
autohide: true,
top offset: 30,
bottom offset: 40,
onDisplay: () =>{},
onHide: () =>{}
})
hide(options = {})
Toast.hide({
onHide: () =>{}
})
Customization of the types of toast
You can add a configuration prop rendering the Toast at the root of your app If you want to add custom types or override existing ones.
Import Toast from 'react-native-toast-message'
const toastConfig ={
'success': (internalstate) =(
<View Style={{ height: 60, width: '100%', background color: 'pink'}}>
<Text>{internalstate.text1}</Text>
</View>
);
'error': () =>{},
'information': () =>{},
'any_custom_type': () =>{}
}
constant root = ()=>}
return (
<Toast config={toastConfig} ref={(ref) => Toast.setRef(ref)}>)
}
export default root
So use the library like before:
Output details:
FAQ’s
1. How to display the Toastinside a Modal?
How are referees tracked?
When you render an instance of at the entry point (root) of your application, a reference is created, and internal tracking is performed.
// Application.jsx
import Toast from 'react-native-toast
app(props) export function {
return (
<>
{/* ... */}
{/* Create a `ref` pointing to this instance of Toast */}
<toast />
</>
);
}
Under the hood, this reference is used when you imperatively call TToast show() or Toast. disguise().
Showing a toast inside a modal
Things get different when you have a Modal. The Modal component sits at the top of the React root view, so the way to display something on top of the Modal is to read it inside the Modal.
This means you need a new instance rendered inside your Modal (in addition to keeping the existing instance outside, at your application's entry point).
import {Modal} from 'react-native'
import Toast from 'react-native-toast-message'
app(props) export function {
const [isModalVisible, setIsModalVisible] = React.useState(false);
return (
<>
{/* ... */}
<toast />
<Visible Modal={isModalVisible}>
+ <toast />
</Mode>
</>
);
}
Everything else works as usual; we show and hide Toasts using the imperative API: Toast. show() or Toast. disguise().
When the Modal is visible, the reference within the Modal will be used; otherwise, the one outside.
The reference is automatically tracked; whichever instance of last had its reference set will be used when shown/hidden.
Notes on react-native-modal or NativeStackNavigator
The same requirements as above will apply when using react-native-modal or a NativeStackNavigator with presentation: 'modal':
{/* The 'Toast' is displayed when neither the native stack display nor the 'Modal' are presented there */}
<toast />
<NativeStackNavigator.Screen>
{/* The `Toast` can displayed when `NativeStackNavigator.Screen` is visible, but `Modal` is NOT visible there. */}
<toast />
<modals>
{/* This `Toast` will displayed when both `NativeStackNavigator.Screen` and `Modal` are visible. */}
<toast />
</Mode>
</NativeStackNavigator.Screen>
</>
2. How to render the Toast when using a navigation library?
Usage with react-navigation
To make the Toastvisible at the top of the navigation view hierarchy, render it as the last child in the view hierarchy (along with the root navigation component):
import { NavigationContainer } from '@react-navigation/native';
export function App() {
return (
<>
<Navigation Container>
{...}
</NavigationContainer>
<toast />
</>
);
}
3. How to mock library to prank test?
show: joke.fn(),
hide: prank.fn()
}));