If your React application consists of a single page, you can easily integrate Termly by adding the cookie banner script directly into the <head>
section of your index.html
file, also known as the template. This script must be the first script on the page to properly control other scripts. Any scripts that appear before the resource-blocker script will not be controllable by it.
Adding Termly to a Single-Page React Application
To install the Termly cookie banner, insert the following script into the <head>
section of your index.html
file:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>React</title> <script type="text/javascript" src="https://app.termly.io/resource-blocker/{UUID}autoBlock=on" ></script> </head> <body></body> </html>
Creating a React Component for the Cookie Banner
Alternatively, if you prefer to manage the script dynamically within your React application, you can create a dedicated component to render the script tag. This method provides better flexibility and ensures the script is properly mounted when needed. However, this approach comes with some risks. If other scripts are hard-coded into the template and load before resource-blocker, they will be executed before Termly can block them.
import { useEffect } from "react"; export default function CookieBanner() { useEffect(() => { const script = document.createElement("script"); script.type = "text/javascript"; script.src = "https://app.termly.io/resource-blocker/{UUID}autoBlock=on"; script.async = true; document.head.appendChild(script); }, []); return null; }
Installing Termly for Multi-Page React Applications
If you are using server-side rendering (such as with Vite or NextJS), please follow the directions in the installation guide for Next.js to ensure proper functionality across multiple pages.