Back to integration guides

July 15, 2026

How to Build an Add to Calendar Button in React and Next.js

A complete step-by-step developer tutorial for creating custom, lightweight Add to Calendar dropdown buttons in React 18/19 and Next.js (App Router) using TypeScript and Tailwind CSS.

Why Every Event App Needs an Add to Calendar Button

When building an event ticketing platform, webinar registration portal, or community app in React or Next.js, providing an "Add to Calendar" button is one of the highest-leverage features you can ship.

Instead of expecting users to remember an event or dig through confirmation emails, an Add to Calendar button allows them to add the event to Google Calendar, Apple Calendar, or Microsoft Outlook with a single tap.

While third-party script tags often inject heavy dependencies, track user cookies, or charge hundreds of dollars a month, building your own lightweight React component or utilizing an open embed is fast, responsive, and fully customizable.

This guide walks you through building a production-ready, zero-dependency Add to Calendar component in React and Next.js.


1. The Core URL Generation Utilities (TypeScript)

Each calendar provider accepts a different URL scheme or file format. Let's create a pure utility file calendar-links.ts that formats dates and builds these links:

export interface CalendarEvent {
  title: string;
  description?: string;
  location?: string;
  startTime: Date;
  endTime: Date;
}
 
// Format a Date object to ISO 8601 basic format (YYYYMMDDTHHMMSSZ)
function formatUtc(d: Date): string {
  return d.toISOString().replace(/[-:]/g, '').split('.')[0] + 'Z';
}
 
// 1. Google Calendar Web Link
export function getGoogleCalendarUrl(e: CalendarEvent): string {
  const params = new URLSearchParams({
    action: 'TEMPLATE',
    text: e.title,
    dates: `${formatUtc(e.startTime)}/${formatUtc(e.endTime)}`,
    details: e.description || '',
    location: e.location || '',
  });
  return `https://calendar.google.com/calendar/render?${params.toString()}`;
}
 
// 2. Microsoft Outlook / Office 365 Web Link
export function getOutlookWebUrl(e: CalendarEvent): string {
  const params = new URLSearchParams({
    path: '/calendar/action/compose',
    rru: 'addevent',
    subject: e.title,
    startdt: e.startTime.toISOString(),
    enddt: e.endTime.toISOString(),
    body: e.description || '',
    location: e.location || '',
  });
  return `https://outlook.office.com/calendar/0/deeplink/compose?${params.toString()}`;
}
 
// 3. Apple Calendar / Universal .ics File Blob
export function generateIcsBlobUrl(e: CalendarEvent): string {
  const clean = (str: string = '') => str.replace(/\\/g, '\\\\').replace(/;/g, '\\;').replace(/,/g, '\\,');
  const lines = [
    'BEGIN:VCALENDAR',
    'VERSION:2.0',
    'PRODID:-//SendToCal//EN',
    'BEGIN:VEVENT',
    `UID:evt_${Date.now()}@yourapp.com`,
    `DTSTAMP:${formatUtc(new Date())}`,
    `DTSTART:${formatUtc(e.startTime)}`,
    `DTEND:${formatUtc(e.endTime)}`,
    `SUMMARY:${clean(e.title)}`,
    `DESCRIPTION:${clean(e.description)}`,
    `LOCATION:${clean(e.location)}`,
    'END:VEVENT',
    'END:VCALENDAR',
  ];
  const blob = new Blob([lines.join('\r\n')], { type: 'text/calendar;charset=utf-8' });
  return URL.createObjectURL(blob);
}

2. Building the Accessible React Dropdown Component

Now, let's create the interactive UI component in React (AddToCalendarButton.tsx) using Tailwind CSS. It supports keyboard accessibility, outside clicks, and mobile screens:

'use client';
 
import React, { useState, useRef, useEffect, useMemo } from 'react';
import {
  CalendarEvent,
  getGoogleCalendarUrl,
  getOutlookWebUrl,
  generateIcsBlobUrl,
} from './calendar-links';
 
export function AddToCalendarButton({ event }: { event: CalendarEvent }) {
  const [isOpen, setIsOpen] = useState(false);
  const containerRef = useRef<HTMLDivElement>(null);
 
  // Close when clicking outside
  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
        setIsOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);
 
  const googleUrl = useMemo(() => getGoogleCalendarUrl(event), [event]);
  const outlookUrl = useMemo(() => getOutlookWebUrl(event), [event]);
  const icsBlobUrl = useMemo(() => generateIcsBlobUrl(event), [event]);
 
  return (
    <div className="relative inline-block text-left" ref={containerRef}>
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-indigo-600 text-white font-medium text-sm shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500/20 transition-all"
        aria-haspopup="true"
        aria-expanded={isOpen}
      >
        <span>๐Ÿ“… Add to Calendar</span>
        <svg
          className={`w-4 h-4 transition-transform ${isOpen ? 'rotate-180' : ''}`}
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>
 
      {isOpen && (
        <div className="absolute right-0 mt-2 w-56 rounded-xl border border-slate-200 bg-white py-1.5 shadow-lg z-50 animate-in fade-in zoom-in-95 duration-100">
          <a
            href={googleUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center gap-2.5 px-4 py-2.5 text-sm text-slate-700 hover:bg-slate-50 transition-colors"
          >
            <span className="w-2.5 h-2.5 rounded-full bg-blue-500" />
            Google Calendar
          </a>
 
          <a
            href={icsBlobUrl}
            download={`${event.title.toLowerCase().replace(/[^a-z0-9]/g, '-')}.ics`}
            className="flex items-center gap-2.5 px-4 py-2.5 text-sm text-slate-700 hover:bg-slate-50 transition-colors"
          >
            <span className="w-2.5 h-2.5 rounded-full bg-slate-900" />
            Apple Calendar (.ics)
          </a>
 
          <a
            href={outlookUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="flex items-center gap-2.5 px-4 py-2.5 text-sm text-slate-700 hover:bg-slate-50 transition-colors"
          >
            <span className="w-2.5 h-2.5 rounded-full bg-sky-600" />
            Outlook / Office 365
          </a>
        </div>
      )}
    </div>
  );
}

3. Alternative: Using the SendToCal Web Component

If you prefer not to manage timezone conversions, CRLF escaping, and mobile edge cases in your application code, you can use SendToCal's official, lightweight Web Component.

Step 1: Include the script in app/layout.tsx

import Script from 'next/script';
 
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        <Script src="https://sendtocal.com/widget.js" strategy="lazyOnload" type="module" />
      </head>
      <body>{children}</body>
    </html>
  );
}

Step 2: Render the button anywhere in your React pages

export function EventHero({ eventToken }: { eventToken: string }) {
  return (
    <div className="my-6">
      <sendtocal-button event-token={eventToken}></sendtocal-button>
    </div>
  );
}

This automatically provides:

  • Fully localized labels (English, Spanish, French, German).
  • Real-time attendee analytics and calendar attribution.
  • Zero-bundle-size footprint for your Next.js application.

Test Your Links Online

Before deploying your component to production, test how your event title, timezone, and description render across different calendar providers.

Try the SendToCal Free Calendar Link Generator to generate test URLs and download sample .ics files in seconds!