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?

[microCMS] Next.js で作ったフロントにシェアボタンを追加する

0
Posted at

やりたいこと

  • 記事ページのみAddToAnyを利用したシェアボタンを追加したい
  • URL以外に、記事タイトルもシェアしたい

AddToAny サイト

X、Facebookなど著名なSNS以外に、日本ならではのはてなブックマークやLINEも追加できる。

コード例

コンポーネント化して必要な箇所で呼び出す形にします。

/components/ShareButton/index.tsx
'use client';
import { useEffect } from 'react';
import Script from 'next/script';

type Props = {
 title?: string;
};
export default function ShareButton({ title = "" }: Props) {
  return (
    <div className="share-button">

      {/* AddToAnyの初期設定オブジェクト(動的にURLとタイトルを渡す) */}
      <Script id="addtoany-config" strategy="afterInteractive">
        {`
          var a2a_config = a2a_config || {};
          a2a_config.linkname = "${title}";
        `}
      </Script>

      {/* シェアボタン本体 */}
      <div className="a2a_kit a2a_kit_size_32 a2a_default_style">
        <a className="a2a_button_x"></a>
        <a className="a2a_button_facebook"></a>
        <a className="a2a_button_hatena"></a>
        <a className="a2a_button_pocket"></a>
        <a className="a2a_button_copy_link"></a>
        <a className="a2a_dd" href="https://www.addtoany.com/share"></a>
      </div>

      {/* AddToAnyのJavaScript本体 */}
      <Script src="https://static.addtoany.com/menu/page.js" strategy="afterInteractive" defer />
    </div>
  );
}

使いたい場所で下記のようにする。

import ShareButton from '../ShareButton';
(略)
<ShareButton title={data.title} />

現場からは以上です。

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?