How Local Notifications Works in React Native(expo)

Anil Verma
2 min readApr 10, 2021

--

Notifications are just like SMS but cost nothing, So most companies/businesses prefer it for sending offers, info to their customer who is using their mobile App.

Notifications Types-
1. Local Notifications
2. Push Notifications

Local Notifications — These are triggered by App itself. Ex. Alarm Reminder, Calendar Reminder

Push Notifications — Received By App and shown back to users locally.

Let’s Do Setup Local Notifications

Step 1. In Your React-Native APP install, following Packages

expo install expo-notifications — Used for Providing functions for notifications

expo install expo-permissions — In IOS devices, for notifications, we have to ask user permission

Step 2. Add “useNextNotificationsApi”: true in App.json for Android Obj like below image

Step 2.

  1. Import both packages in your js file
    import * as Notifications from ‘expo-notifications’;
    import * as Permissions from ‘expo-permissions’;

2. Add a button on which click, you want to trigger local notification

<Button onPress={triggerNotifications} title="Trigger Local Notifications" color="#841584" accessibilityLabel="Trigger Local Notifications"/>

3. Create function triggerNotifications and use like

const triggerNotifications = async () => {
await Notifications.scheduleNotificationAsync({
content: {
title: “You’ve got mail! 📬”,
body: ‘Here is the notification body’,
data: { data: ‘goes here’ },
},
trigger: { seconds: 2 },
});
}

for IOS Add the following function for permission-

export default function App() {
useEffect(() => {
Permissions.getAsync(Permissions.NOTIFICATIONS).then((statusObj) => {
if (statusObj.status !== ‘granted’) {
return Permissions.askAsync(Permissions.NOTIFICATIONS)
}
return statusObj;
}).then((statusObj) => {
if (statusObj.status !== ‘granted’) {
return;
}
})
}, [])

till this setup, your local notification is ready for background, which means if you trigger/click on the button then the notification will trigger only if your app is closed. So click on the button and move to some other app or home screen you will able to see notifications.

4. Enable notification in the foreground too.

Put below function outside of your functional component on top after import statements

Notifications.setNotificationHandler({
handleNotification: async () => {
return {
shouldShowAlert: true
}}
})

Now your app is ready for Local notifications.

Thanks for reading, Happy Coding… 👏👏

--

--

Anil Verma

Hi there 👋, I am Anil Verma, a full stack web developer, and JavaScript enthusiast. 👥 Ask me anything about web development. web- https://anilvermaspeaks.in/