Add Event in Device’s Calendar from React Native App for Android and iOS

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 in 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, 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 in 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 in 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 init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

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

After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but need to install pods and to install cocoa pods use

cd ios && pod install && cd ..

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:

  1. Get Current Time in 12 hours Format AM PM
  2. CountDown Timer using react-native-countdown-component
  3. 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

//Example to add event in Device Calendar
import React, { Component } from 'react';
//Import React
import {
  StyleSheet,
  Text,
  View,
  Button,
  TextInput,
  TouchableOpacity,
} from 'react-native';
//Import basic react native components
import * as AddCalendarEvent from 'react-native-add-calendar-event';
//Import library for AddCalendarEvent
import moment from 'moment';
//Import moment.js to deal with time

const EVENT_TITLE = 'Lunch';
const TIME_NOW_IN_UTC = moment.utc();

const utcDateToString = (momentInUTC: moment): string => {
  let s = moment.utc(momentInUTC).format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
  return s;
};

export default class App extends Component {
  state = { text: '' };
  render() {
    return (
      <View style={styles.container}>
        <Text style={{ fontSize: 20, textAlign: 'center', marginVertical: 10 }}>
          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.button}
          onPress={() => {
            App.addToCalendar(EVENT_TITLE, TIME_NOW_IN_UTC);
          }}>
          <Text>Add Event to Calendar</Text>
        </TouchableOpacity>
        <TextInput
          style={styles.input}
          placeholder="enter event id"
          onChangeText={text => this.setState({ text })}
          value={this.state.text}
        />
        <View style={{ flexDirection: 'row' }}>
          <TouchableOpacity
            style={styles.buttonHalf}
            onPress={() => {
              App.editCalendarEventWithId(this.state.text);
            }}>
            <Text style={{ textAlign: 'center' }}>Edit Event</Text>
          </TouchableOpacity>
          <View style={{ margin: 5 }} />
          <TouchableOpacity
            style={styles.buttonHalf}
            onPress={() => {
              App.showCalendarEventWithId(this.state.text);
            }}>
            <Text style={{ textAlign: 'center' }}>View Event</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  static addToCalendar = (title: string, startDateUTC: moment) => {

    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);
      });
  };

  static editCalendarEventWithId = (eventId: string) => {
    const eventConfig = {
      eventId,
    };

    AddCalendarEvent.presentEventEditingDialog(eventConfig)
      .then(eventInfo => {
        alert('eventInfo -> ' + JSON.stringify(eventInfo));
      })
      .catch((error: string) => {
        alert('Error -> ' + error);
      });
  };

  static showCalendarEventWithId = (eventId: string) => {
    const eventConfig = {
      eventId,
      allowsEditing: true,
      allowsCalendarPreview: true,
      navigationBarIOS: {
        tintColor: 'orange',
        backgroundColor: 'green',
      },
    };

    AddCalendarEvent.presentEventViewingDialog(eventConfig)
      .then(eventInfo => {
        alert('eventInfo -> ' + JSON.stringify(eventInfo));
      })
      .catch((error: string) => {
        alert('Error -> ' + error);
      });
  };
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    padding: 40,
  },
  heading: {
    fontSize: 14,
    textAlign: 'center',
    margin: 10,
  },
  button: {
    alignItems: 'center',
    backgroundColor: '#DDDDDD',
    padding: 10,
    width: '100%',
    marginTop: 16,
  },
  buttonHalf: {
    alignItems: 'center',
    backgroundColor: '#DDDDDD',
    padding: 10,
    flex: 1,
  },
  input: {
    height: 40,
    width: '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
To run the project on an Android Virtual Device or on real debugging device
react-native run-android
or on the iOS Simulator by running
react-native run-ios (macOS only).

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 you 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. 🙂

 


Related Posts

6 thoughts on “Add Event in Device’s Calendar from React Native App for Android and iOS”

  1. 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

    Reply
    • 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.

      Reply
  2. 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?

    Reply
  3. 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

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.