LoginSignup
1
0

React x react-ga4 x CookieConsent

Last updated at Posted at 2023-05-24

インストール

npm i react-ga4
npm i react-cookie-consent

コード

App.jsx
import { Cookies, getCookieConsentValue } from 'react-cookie-consent';
import ReactGA from 'react-ga4';
// ...
const cookieName = 'accept-cookie';
const App = () => {
  const acceptCookie = useCallback(() => {
    ReactGA.initialize(process.env.REACT_APP_ANALYTICS_KEY);
  }, []);
  const declineCookie = useCallback(() => {
    const cookie = Cookies.get();
    Object.keys(cookie).forEach((key) => {
      if (key !== cookieName) Cookies.remove(key);
    });
  }, []);
  useEffect(() => {
    if (getCookieConsentValue(cookieName) === 'true') {
      ReactGA.initialize(process.env.REACT_APP_ANALYTICS_KEY);
    } else {
      const cookie = Cookies.get();
      Object.keys(cookie).forEach((key) => {
        if (key !== cookieName) Cookies.remove(key);
      });
    }
  }, []);
  // ...
  return(
    // ...
    <CookieConsent
      location='bottom'
      buttonText={/* 同意ボタンの文字列 */}
      declineButtonText={/* 拒否ボタンの文字列 */}
      cookieName={/* クッキーの名前 */}
      style={/* css */}
      buttonStyle={/* css */}
      enableDeclineButton={/* 拒否ボタンを表示するか */}
      expires={/* 有効期間 */}
      onAccept={acceptCookie}
      onDecline={declineCookie}
    >
      {/* Cookieの使用について同意を求める文章 */}
    </CookieConsent>
  )
};

文章例

当サイトではアクセス解析のためにCookieを使用しています。Cookieを許可するか否かを選択してください。
Cookieの利用についてはプライバシーポリシー及び利用規約をご確認ください。

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