Add Event in Device’s Calendar
Here is an Example to Add Event in Device’s Calendar from React Native App for Android and iOS. In this example, you will see how easily you can add any event to your device’s calendar from React Native App. While planning this example I was thinking it is going to be very tricky to open the calendar of the device and how to the callback for the success of addition or cancellation but after finding react-native-add-calendar-event
library everything became very easy.
This library starts an activity (in Android) or shows a modal window (for iOS) to add, view, or edit events in the device’s calendar. It provides a promise in return, and with the help of that you can find out if a new event was added and can get its id.
How to add an event in the calendar?
const eventConfig = {
title,
startDate: utcDateToString(startDateUTC),
endDate:
utcDateToString(moment.utc(startDateUTC).add(1, 'hours')),
notes: 'tasty!',
navigationBarIOS: {
tintColor: 'orange',
backgroundColor: 'green',
titleColor: 'blue',
},
};
AddCalendarEvent.presentEventCreatingDialog(eventConfig)
.then(
(eventInfo: {
calendarItemIdentifier: string,
eventIdentifier: string,
}) => {
alert('eventInfo -> ' + JSON.stringify(eventInfo));
}
)
.catch((error: string) => {
// handle error such as when user rejected permissions
alert('Error -> ' + error);
});
In this example, we will show the title and the time of the event on the top of the screen which we are going to add to the calendar. Event time will be the current time to see the event notification.
We will have an “add an event to calendar” button and on click of it, we will add the event to the calendar. After clicking on it you will see the prefilled calendar screen with the parameter provided in your app.
After adding the event when you come back you will see the details related to the event with the event id. you will also see an input to put this calendar id to edit or view the event. So let’s start with the example and see how to add the event in the device’s calendar.
To Make a React Native App
Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react native command line interface to make our React Native App.
If you have previously installed a global react-native-cli package, please remove it as it may cause unexpected issues:
npm uninstall -g react-native-cli @react-native-community/cli
Run the following commands to create a new React Native project
npx react-native init ProjectName
If you want to start a new project with a specific React Native version, you can use the --version argument:
npx react-native init ProjectName --version X.XX.X
Note If the above command is failing, you may have old version of react-native
or react-native-cli
installed globally on your pc. Try uninstalling the cli and run the cli using npx.
This will make a project structure with an index file named App.js in your project directory.
Installation of Dependencies
To install the dependencies open the terminal and jump into your project using
cd ProjectName
1. To add an event in the device’s calendar we will use AddCalendarEvent
component and for that install react-native-add-calendar-event
dependency
npm install react-native-add-calendar-event --save
2. In this example, we are dealing with the date-time and to handle those date time we will use moment.js
in our project, to import moment in our project let’s import moment using
npm install moment --save
This command will copy all the dependencies into your node_module directory.
CocoaPods Installation
Please use the following command to install CocoaPods
npx pod-install
Time format for the event
If you are working with any date-time in JavaScript you need a proper time format and according to the standard, we should use UTC format which us a standard format and used in many places. In this example also we have used UTC time formate for our start and end date.
startDate - UTC, format: 'YYYY-MM-DDTHH:mm:ss.SSSZ'
endDate - UTC, format: 'YYYY-MM-DDTHH:mm:ss.SSSZ'
As I have told you earlier that we are going to use moment.js for that so here is how you can get the current date-time in UTC format using moment.js0
const TIME_NOW_IN_UTC = moment.utc();
To know more about moment.js you can visit:
- Get Current Time in 12 hours Format AM PM
- CountDown Timer using react-native-countdown-component
- Get Current Date Time
Code to Add Event in Device’s Calendar
Open App.js in any code editor and replace the code with the following code
App.js
// Add Event in Device’s Calendar from React Native App for Android and iOS
// https://aboutreact.com/react-native-add-event-in-device-calendar/
// import React in our code
import React, {useState} from 'react';
// import all the components we are going to use
import {
SafeAreaView,
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity,
} from 'react-native';
//Import library for AddCalendarEvent
import * as AddCalendarEvent from 'react-native-add-calendar-event';
//Import moment.js to deal with time
import moment from 'moment';
const EVENT_TITLE = 'Lunch';
const TIME_NOW_IN_UTC = moment.utc();
const utcDateToString = (momentInUTC) => {
let s = moment.utc(momentInUTC)
.format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
return s;
};
const addToCalendar = (title, startDateUTC) => {
const eventConfig = {
title,
startDate: utcDateToString(startDateUTC),
endDate:
utcDateToString(moment.utc(startDateUTC).add(1, 'hours')),
notes: 'tasty!',
navigationBarIOS: {
tintColor: 'orange',
backgroundColor: 'green',
titleColor: 'blue',
},
};
AddCalendarEvent.presentEventCreatingDialog(eventConfig)
.then((eventInfo) => {
alert('eventInfo -> ' + JSON.stringify(eventInfo));
})
.catch((error) => {
// handle error such as when user rejected permissions
alert('Error -> ' + error);
});
};
const editCalendarEventWithId = (eventId) => {
if (!eventId) {
alert('Please Insert Event Id');
return;
}
const eventConfig = {
eventId,
};
AddCalendarEvent.presentEventEditingDialog(eventConfig)
.then((eventInfo) => {
alert('eventInfo -> ' + JSON.stringify(eventInfo));
})
.catch((error) => {
alert('Error -> ' + error);
});
};
const showCalendarEventWithId = (eventId) => {
if (!eventId) {
alert('Please Insert Event Id');
return;
}
const eventConfig = {
eventId,
allowsEditing: true,
allowsCalendarPreview: true,
navigationBarIOS: {
tintColor: 'orange',
backgroundColor: 'green',
},
};
AddCalendarEvent.presentEventViewingDialog(eventConfig)
.then((eventInfo) => {
alert('eventInfo -> ' + JSON.stringify(eventInfo));
})
.catch((error) => {
alert('Error -> ' + error);
});
};
const App = () => {
const [text, setText] = useState('');
return (
<SafeAreaView style={styles.container}>
<View style={styles.container}>
<Text style={styles.titleStyle}>
Example to Add Event in Google Calendar
from React Native App
</Text>
<Text style={styles.heading}>
Event title: {EVENT_TITLE}
{'\n'}
Event Date Time: {
moment.utc(TIME_NOW_IN_UTC).local().format('lll')
}
</Text>
<TouchableOpacity
style={[styles.buttonStyle, {minWidth: '100%'}]}
onPress={() => {
addToCalendar(EVENT_TITLE, TIME_NOW_IN_UTC);
}}>
<Text style={styles.buttonTextStyle}>
Add Event to Calendar
</Text>
</TouchableOpacity>
<TextInput
style={styles.inputStyle}
placeholder="enter event id"
onChangeText={(text) => setText(text)}
value={text}
/>
<View style={{flexDirection: 'row'}}>
<TouchableOpacity
style={styles.buttonStyle}
onPress={() => {
editCalendarEventWithId(text);
}}>
<Text style={styles.buttonTextStyle}>
Edit Event
</Text>
</TouchableOpacity>
<View style={{margin: 5}} />
<TouchableOpacity
style={styles.buttonStyle}
onPress={() => {
showCalendarEventWithId(text);
}}>
<Text style={styles.buttonTextStyle}>
View Event
</Text>
</TouchableOpacity>
</View>
</View>
</SafeAreaView>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#307ecc',
padding: 16,
},
heading: {
color: 'white',
fontSize: 16,
textAlign: 'center',
margin: 10,
},
buttonStyle: {
paddingVertical: 10,
paddingHorizontal: 30,
backgroundColor: '#f5821f',
margin: 15,
},
buttonTextStyle: {
color: 'white',
textAlign: 'center',
},
buttonHalfStyle: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
flex: 1,
},
titleStyle: {
color: 'white',
textAlign: 'center',
fontSize: 20,
marginBottom: 20,
},
inputStyle: {
height: 40,
minWidth: '100%',
marginBottom: 10,
marginTop: 30,
padding: 10,
backgroundColor: '#ffe6e6',
},
});
To Run the React Native App
Open the terminal again and jump into your project using.
cd ProjectName
1. Start Metro Bundler
First, you will need to start Metro, the JavaScript bundler that ships with React Native. To start Metro bundler run following command:
npx react-native start
Once you start Metro Bundler it will run forever on your terminal until you close it. Let Metro Bundler run in its own terminal. Open a new terminal and run the application.
2. Start React Native Application
To run the project on an Android Virtual Device or on real debugging device:
npx react-native run-android
or on the iOS Simulator by running (macOS only)
npx react-native run-ios
Output Screenshots
Android
iOS
This is how you can add an event in the device’s calendar from React Native app for Android and iOS. If you have any doubts or want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned! Hope you liked it. 🙂
Hi, Im new with react native I wonder if you can help me. Im trying to connect my app into device primary calendar and save event but the thing is i need to bypass the save button of the calendar app. I need to save it immediately and don’t show/ open the device calendar app. I really appreciate if you can help me. Thank you
Hi, Shiela, Device calendar do not provide the direct APIs to save the event due to the security reasons. Here we have used a bridge to connect to the calendar and passing some value to fill the fields. I tried to find the option for direct scheduling but unable to find any.
Hello Snehal,
Thanks in advance, I am new to react-native. In my app, I would like to access the google calendar events. Could you help me out?
Please find the links below and try to make it. If you still have any issue then you can comment again I’ll try to help you
https://www.npmjs.com/package/react-google-calendar-events-list
https://www.npmjs.com/package/react-native-calendar-events
https://github.com/wix/react-native-calendars/issues/416#issuecomment-413202491
Hi Sir Hope so You are fine. i want to set alarm on specific time on my app. any library or method. i implement react native push notification for schedule and its working fine but its working on foreground not background. the purpose of alarm not fulfil. kindly suggest me good thing. Thanks a lot sir
I agree with you.
I tried to find the solution for that but there is not a proper solution for that. Maybe you have to make a bridge and have to implement a native functionality.