0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JSXでワンクリックカレンダー登録(.ics)を行うボタンを実装する

Last updated at Posted at 2024-06-11

やりたいこと

ホームページ上のボタンからワンクリックでiPhoneなどのカレンダーアプリに登録できるようにする。

例えば、以下のWEBサイトでは、音楽ライブの日程をワンクリックで追加することができます。
https://www.sano-maoko.jp/live

具体的な動作
  1. HP(佐野真於子さん)の画面
    以下の画面の「カレンダーに追加」ボタンを押すと、
    クリック画面

  2. クリック後の画面
    iPhoneの場合、以下のような画面が開きます。表示されたイベントはUI株の「カレンダーに追加」をタップするとカレンダーに追加されます。
    HP画面

概念

  • PC上でカレンダー情報を表現する際の共通のフォーマットである.ics(iCalender)ファイルを活用
  • ボタンクリック時に.icsファイルをダウンロードする処理を実装することで、クライアント側が勝手に判断して自身のカレンダーにイベントを追加してくれます。

実装

ここからは、JSX(Next.js)で上記の動作を実行するための実装を説明します。(Reactでも同様です。)

環境

  "dependencies": {
    "ics": "^3.7.2",
    "next": "^14.2.3",
    "react": "^18.3.1",
    "react-dom": "^18.3.1"
  },

インストール

まず、.icsファイルの作成用npmパッケージをダウンロードします。
https://www.npmjs.com/package/ics

npm

npm install ics

ソースコード

以下のように実装します。JSXの環境下で実装しています。

Live.tsx
import { EventAttributes, createEvent } from "ics";

export const Live: NextPage = () => {
  // ダウンロード用URL
  const [url, setUrl] = useState("");

  // 初期化
  useEffect(() => {
    createCalenderEvent();
  });

  // カレンダーイベントを作成する。
  async function createCalenderEvent() {
    // イベントの情報
    const eventSource: EventAttributes = {
      title: "title",
      location: "name",
      start: [
        liveDate.getFullYear(),
        liveDate.getMonth() + 1,
        liveDate.getDate(),
        liveDate.getHours(),
        liveDate.getMinutes(),
      ],
      duration: { hours: 2 },
    };

    // ファイルセット
    const filename = "live.ics";
    const event = await createEvent(eventSource).value;
    if (event !== undefined) {
      const file = new File([event], filename, { type: "text/calendar" });
      const url = URL.createObjectURL(file);
      setUrl(url);
    }
  }

  // ダウンロード処理
  function download() {
    const link = document.createElement("a");
    link.href = url;
    link.download = "live.ics";
    link.click();
  }

  return (
    <>
      <button onClick={() => download()}>Download</button>
    </>
  );
};

カレンダーイベントは、MIMEタイプ"text/calender"で表されるテキストファイルです。

説明

  • useEffectでcreateCalenderEventを呼び出すことでカレンダーファイルの作成/リンクの取得をします。初期化時に、.icsファイルを作成し、ダウンロード用urlを作成します。ダウンロード用urlをstateに保存しておきます。
  • 上記で作成したカレンダーイベントをダウンロードするために、download関数を呼び出します。download関数では、ダミーのリンクエレメントを作成し、作成したカレンダーイベントをリンク先にセットすることで、ダウンロード処理を実施します。

まとめ

本記事では、HP上からワンクリックでイベントを追加するための方法を説明しました。.icsファイルを作成し、ダウンロードできるようにすることで実現できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?