How to integrate a React calendar component to streamline scheduling

12 min read

Streamline scheduling with a React calendar component: A step-by-step guide

In today’s fast-paced digital world, integrating a calendar into your application is more critical than ever. It allows users to easily schedule and manage appointments, meetings, and events directly within your app, significantly enhancing their overall experience and productivity. With Nylas, this integration becomes seamless and efficient, simplifying the process and reducing development time. Let’s explore integrating a React calendar component to streamline scheduling, leveraging Nylas’ powerful capabilities to boost your app’s functionality.

What is a React calendar component?

React calendar components are reusable UI elements that enable users to view, schedule, and manage events within a React application. Integrating this with the Nylas Calendar API enhances the component’s capabilities by enabling seamless synchronization with users’ calendars, real-time availability checks, and automatic event updates. This combination simplifies development, saves time, and provides a robust, professional scheduling solution for your app.

Setting up your React application

Before diving into creating your React application, make sure you have the following prerequisites in place:

  1. Node.js and npm: React relies on Node.js and its package manager npm (or yarn). You can download and install Node.js from the official website. This installation will also include npm.
  2. Code editor: A good code editor like Visual Studio Code (VS Code) can make your coding experience much smoother. You can download it here.
  3. Basic understanding of JavaScript: While React simplifies many things, a basic understanding of JavaScript will help you navigate your project more easily.

Once you have the prerequisites ready, follow these steps to create a new React application:

1. Install Create React App

  • Open your terminal or command prompt.
  • Run the following command to install Create React App globally on your system:
npx create-react-app my-app

Replace “my-app” with the name you want for your application. This command creates a new React project with all the necessary files and configurations.

2. Navigate to your project directory

  • After the installation is complete, navigate to your project directory using:
cd my-app

Again, replace “my-app” with your chosen project name.

3. Start the development server

  • To see your new React application in action, start the development server by running:
npm start

This command will open your default browser and navigate to “http://localhost:3000”, where you can see your React app up and running.

Now that your React application is set up, you can start customizing it. Open your project in your code editor and modify the files in the “src” directory to begin building your unique application.

Integrating a React calendar component

To get started with integrating a calendar into your React application, we’ll use a popular library called “react-big-calendar”. This library is well-regarded for its flexibility and comprehensive feature set, making it an excellent choice for our needs.

Step 1: Install the library

First, we need to install “react-big-calendar” along with “moment” which is required for date management.

npm install react-big-calendar moment

This will add the necessary packages to your project, allowing you to start using the calendar component.

Step 2: Basic setup and configuration

Now, let’s configure the calendar component in your “App.js” file. Open “App.js” in your code editor and set up the basic structure:

1. Create a Calendar Component

Create a new file “CalendarComponent.js” in the “src” directory of your project.

import React from 'react';
import { Calendar, momentLocalizer } from 'react-big-calendar';
import moment from 'moment';
import 'react-big-calendar/lib/css/react-big-calendar.css';

const localizer = momentLocalizer(moment);

const CalendarComponent = ({ events }) => {
  return (
    <div style={{ height: '500px' }}>
      <Calendar
        localizer={localizer}
        events={events}
        startAccessor="start"
        endAccessor="end"
        style={{ height: 500 }}
      />
    </div>
  );
};

export default CalendarComponent;

2. Add the calendar component to your app

Update your “App.js” file to include the “CalendarComponent” and pass the events to it.

import React, { useState, useEffect } from 'react';
import CalendarComponent from './CalendarComponent';
import './App.css';

const App = () => {
  const [events, setEvents] = useState([]);

  useEffect(() => {
    // Example events
    const exampleEvents = [
      {
        start: new Date(),
        end: new Date(new Date().setHours(new Date().getHours() + 1)),
        title: 'Sample Event',
      },
    ];
    setEvents(exampleEvents);
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <h1>React Calendar Integration</h1>
      </header>
      <main>
        <CalendarComponent events={events} />
      </main>
    </div>
  );
};

export default App;

With these steps, you’ve successfully installed and configured the frontend part of your React calendar component. Now, your application has an integrated calendar component that can display events. However, it will not yet be fully functional for adding, updating, and deleting events. In the following sections, we will give it the backend functionality with the help of the Nylas API.

Nylas integration for React calendar component

Integrating a calendar component into your application can greatly enhance its functionality, but integrating it with a robust API like Nylas takes it to the next level. Nylas offers a seamless way to access and manage email, calendar, and contact data across various providers through a single API. This makes it incredibly efficient for developers to build powerful scheduling features without the hassle of handling multiple integrations.

Step 1: Sign up for Nylas and set up the sandbox environment

To get started with Nylas, you’ll need to sign up for an account and set up the sandbox environment for testing.

1. Sign up for Nylas:

  • Visit the Nylas Dashboard and sign up for a free account. It’s a quick process, and you’ll be up and running in no time.

2. Access the sandbox environment:

  • Once you’ve signed up and logged in to the Nylas Dashboard, you’ll be directed to the sandbox environment. Here, you will obtain your Client ID and API key, which you will use to authenticate your application.

Step 2: Configure the Nylas API in your React application

1. Install the Nylas SDK

First, you need to install the Nylas SDK in your React project:

npm install nylas

2. Set up environment variables

Create a “.env” file in the root of your project and add the following environment variables:

REACT_APP_NYLAS_CLIENT_ID=your-client-id
REACT_APP_NYLAS_API_KEY=your-api-key
REACT_APP_NYLAS_ACCESS_TOKEN=your-access-token

3. Configure Nylas in Your React application

Create a configuration file, e.g., “nylasConfig.js”, to set up Nylas:

import Nylas from 'nylas';

Nylas.config({
  clientId: process.env.REACT_APP_NYLAS_CLIENT_ID,
  accessToken: process.env.REACT_APP_NYLAS_ACCESS_TOKEN,
});

export default Nylas;

4. Create a component to check availability

Create a new file named “CheckAvailability.js” inside the “src” directory and paste the following code:

import React, { useState, useEffect } from 'react';
import Nylas from 'nylas';

const CheckAvailability = () => {
  const [availability, setAvailability] = useState(null);
  const [error, setError] = useState(null);

  const checkAvailability = async () => {
    try {
      const nylas = Nylas.with(process.env.REACT_APP_NYLAS_ACCESS_TOKEN);

      const availability = await nylas.calendars.checkAvailability({
        start_time: new Date().toISOString(),
        end_time: new Date(new Date().getTime() + 24 * 60 * 60 * 1000).toISOString(),
        interval_minutes: 60,
        duration_minutes: 30,
        emails: ['user@example.com'], // Replace with actual email addresses
      });

      setAvailability(availability);
    } catch (error) {
      setError(error.message);
    }
  };

  useEffect(() => {
    checkAvailability();
  }, []);

  return (
    <div>
      <h1>Check Calendar Availability</h1>
      <button onClick={checkAvailability}>Refresh Availability</button>
      {availability && <pre>{JSON.stringify(availability, null, 2)}</pre>}
      {error && <p>Error: {error}</p>}
    </div>
  );
};

export default CheckAvailability;

This code will integrate Nylas with your calendar component to fetch and display availability data. 

By following these steps, you have successfully set up and configured Nylas with your React calendar component. Your application now includes an integrated calendar that can display events and check availability. In the following section, we will enhance this functionality further by adding the ability to create, update, and delete events, making your calendar fully interactive and robust.

Connecting Nylas to your calendar component

Connecting Nylas to your React calendar component allows you to seamlessly fetch and manage calendar events. This section will guide you through the process of fetching events, updating your calendar component to display them, and implementing features like event creation, deletion, and updates.

Step 1: Fetch calendar events

To fetch events from Nylas, you’ll use the Nylas SDK to send a request to the Nylas events endpoint. Here’s a basic setup to fetch events:

import React, { useEffect } from 'react';
import Nylas from 'nylas';

const FetchEvents = ({ onEventsFetched }) => {
  useEffect(() => {
    const fetchEvents = async () => {
      try {
        const nylasClient = new Nylas({
          clientSecret: process.env.REACT_APP_NYLAS_API_KEY,
        });
        const events = await nylasClient.events.list({ calendar_id: 'your-calendar-id' });

        const formattedEvents = events.map(event => ({
          id: event.id,
          start: new Date(event.when.start_time),
          end: new Date(event.when.end_time),
          title: event.title,
        }));

        onEventsFetched(formattedEvents);
      } catch (error) {
        console.error('Error fetching events:', error);
      }
    };

    fetchEvents();
  }, [onEventsFetched]);

  return null;
};

export default FetchEvents;

Step 2: Implement features

1. Add events

To add events, you will create an “AddEventForm.js” file in the “src” directory and paste the following code:

import React, { useState } from 'react';

const AddEventForm = ({ onEventAdded }) => {
  const [title, setTitle] = useState('');
  const [startTime, setStartTime] = useState('');
  const [endTime, setEndTime] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const response = await fetch('http://localhost:5000/api/events', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${process.env.REACT_APP_NYLAS_ACCESS_TOKEN}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          title,
          when: {
            start_time: new Date(startTime).toISOString(),
            end_time: new Date(endTime).toISOString(),
          },
        }),
      });

      if (!response.ok) {
        throw new Error('Failed to add event');
      }

      const newEvent = await response.json();
      onEventAdded(newEvent);
    } catch (error) {
      console.error('Error creating event:', error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Event Title"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        required
      />
      <input
        type="datetime-local"
        value={startTime}
        onChange={(e) => setStartTime(e.target.value)}
        required
      />
      <input
        type="datetime-local"
        value={endTime}
        onChange={(e) => setEndTime(e.target.value)}
        required
      />
      <button type="submit">Add Event</button>
    </form>
  );
};

export default AddEventForm;

2. Update events

To update events, you will create an “UpdateEventForm.js” file in the “src ” directory and paste the following code:

import React, { useState } from 'react';

const UpdateEventForm = ({ event, onUpdate }) => {
  const [title, setTitle] = useState(event.title);
  const [startTime, setStartTime] = useState(new Date(event.start).toISOString().slice(0, -1));
  const [endTime, setEndTime] = useState(new Date(event.end).toISOString().slice(0, -1));

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const response = await fetch(`http://localhost:5000/api/events/${event.id}`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${process.env.REACT_APP_NYLAS_ACCESS_TOKEN}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          title,
          when: {
            start_time: new Date(startTime).toISOString(),
            end_time: new Date(endTime).toISOString(),
          },
        }),
      });

      if (!response.ok) {
        throw new Error('Failed to update event');
      }

      const updatedEvent = await response.json();
      onUpdate(updatedEvent);
    } catch (error) {
      console.error('Error updating event:', error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        required
      />
      <input
        type="datetime-local"
        value={startTime}
        onChange={(e) => setStartTime(e.target.value)}
        required
      />
      <input
        type="datetime-local"
        value={endTime}
        onChange={(e) => setEndTime(e.target.value)}
        required
      />
      <button type="submit">Update Event</button>
    </form>
  );
};

export default UpdateEventForm;

3. Delete events

To delete events, you will create a “DeleteEventButton.js” file in the “src ” directory and paste the following code:

import React from 'react';

const DeleteEventButton = ({ eventId, onDelete }) => {
  const handleDelete = async () => {
    try {
      const response = await fetch(`http://localhost:5000/api/events/${eventId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${process.env.REACT_APP_NYLAS_ACCESS_TOKEN}`,
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error('Failed to delete event');
      }

      onDelete(eventId);
    } catch (error) {
      console.error('Error deleting event:', error);
    }
  };

  return <button onClick={handleDelete}>Delete</button>;
};

export default DeleteEventButton;

Step 3: Handling CORS with a server

To handle CORS issues, you will create a simple Express server that will act as a proxy between your React app and the Nylas API. 

1. Create a “server.js” file in the root directory of your project and paste the following code:

const express = require('express');
const request = require('request');
const cors = require('cors');

const app = express();
const PORT = 5000;

Use the CORS middleware

app.use(cors());

app.use(express.json());

app.use('/api', (req, res) => {
  const url = `https://api.nylas.com${req.url}`;
  req.pipe(request(url)).pipe(res);
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

2. Run the server

Open your terminal and run:

node server.js

This Express server listens on port 5000, using CORS middleware to allow requests from your React app. It proxies requests from the “/api” endpoint to the Nylas API, bypassing CORS restrictions by routing them through your server.

By following these steps, you’ll integrate Nylas into your React application, enabling users to view and manage their calendar events seamlessly. The server acts as a bridge to handle CORS issues, ensuring smooth communication between your front end and Nylas.

Maximize user engagement with a React calendar component and Nylas

We’ve covered quite a bit in this journey! From setting up your React app and integrating a calendar component to connecting with Nylas for added functionality, you’ve built a robust calendar tool. Remember, this is just the start. Nylas offers many possibilities, and your creativity is the limit.

We encourage you to dive deeper into the Nylas API. Explore other features like email and contacts integration, and see how you can enhance your application further. The sandbox environment is a great place to experiment without any commitment, so take advantage of it.

Ready to take the next step? Sign up for Nylas, explore the documentation, and build the integrations to transform your app into a productivity powerhouse. Happy coding!

Related resources

How to build email templates with React

Learn how to build email templates using React.

How to create a scheduling calendar to organize events: A step-by-step guide

Discover how to create an event schedule with minimal effort. Create events, update them and distribute them with ease.

Introducing the new Nylas Scheduler: Experience the future of in-app scheduling

Get access to modular, customizable, and native components for bespoke scheduling in your app.