インストール
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の利用についてはプライバシーポリシー及び利用規約をご確認ください。