React (Vite / CRA)
This guide explains how to integrate Rybbit with your client-side React application, such as those created with Create React App (CRA) or Vite.
How to Add Rybbit to Your React App
The recommended and simplest method to add the Rybbit tracking script is directly in your index.html
file. This ensures the script is loaded early and reliably.
Adding to public/index.html
(or index.html
for Vite)
This is the most straightforward method and ensures the script is loaded early.
1. Retrieve Your Tracking Script
Navigate to your Rybbit dashboard to obtain your code snippet. It will look like this:
<script
src="https://app.rybbit.io/api/script.js"
data-site-id="YOUR_SITE_ID"
async
defer
></script>
Remember to replace YOUR_SITE_ID
with your actual Site ID.
2. Locate Your index.html
File
- For Create React App (CRA): This file is typically located at
public/index.html
. - For Vite (React template): This file is typically located at the root of your project as
index.html
.
3. Add the Snippet to index.html
Open your index.html
file and paste the Rybbit tracking snippet just before the closing </head>
tag or </body>
tag. Placing it in the <head>
allows it to load sooner.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <!-- Example for CRA -->
<!-- Other meta tags and links -->
<title>My React App</title>
<!-- Rybbit Tracking Snippet -->
<script
src="https://app.rybbit.io/api/script.js"
data-site-id="YOUR_SITE_ID"
async
defer
></script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!-- If you prefer, you can also place the script here, before </body> -->
</body>
</html>
Make sure to replace YOUR_SITE_ID
with your actual Site ID.
4. Verify Installation
After deploying your application, open your Rybbit dashboard to see if data is being received. You can also check your browser’s network tab to ensure script.js
is loaded.
SPA Page View Tracking: Rybbit’s tracking script is designed to automatically detect route changes in most modern SPAs (including those using React Router or similar libraries) and track them as page views. If you find that page views are not being tracked correctly after navigation, you might need to manually trigger page views using window.rybbit.trackPageview()
after each route change. However, try the standard installation first.
Custom Event Tracking
Once the script is installed, you can track custom events from any of your React components:
function MyComponent() {
const handleButtonClick = () => {
if (window.rybbit) {
window.rybbit.trackEvent('button_click', { category: 'CTA', label: 'Learn More' });
}
};
return <button onClick={handleButtonClick}>Learn More</button>;
}
Ensure window.rybbit
is available before calling its methods, especially if you load the script dynamically or have strict Content Security Policies.