Embedding Reach into your application is straightforward and flexible.
Creating a Container Element
First, create a div element that will serve as the container for the Reach interface:
<div id="reach-embed" style="height: 600px; width: 100%;"></div>
We recommend a minimum height of 500px for optimal user experience, but the
interface is fully responsive.
Importing the SDK
There are two approaches to importing the SDK:
Option 1: Dynamic Script Loading (Recommended for React/Next.js)
const importScript = resourceUrl => {
const script = document.createElement('script');
script.src = resourceUrl;
script.type = 'module';
script.async = true;
document.body.appendChild(script);
return script;
};
// Usage
const script = importScript(
'https://cdn.embedreach.com/iframe/sdk/sdk.es.js',
);
For React or Next.js applications, be sure to clean up the script on component unmount:
useEffect(() => {
const script = importScript('https://cdn.embedreach.com/iframe/sdk/sdk.es.js');
return () => {
if (script && document.body.contains(script)) {
document.body.removeChild(script);
}
};
}, []);
Option 2: Using a Script Tag
<script
type="module"
src="https://cdn.embedreach.com/iframe/sdk/sdk.es.js"></script>
Initializing the SDK
Once the script is loaded, initialize the SDK with your configuration:
const loadReachSDK = config => {
try {
const sdk = new window.ReachSDK(config);
return sdk;
} catch (err) {
console.error('Failed to initialize ReachSDK:', err);
throw err;
}
};
// Example configuration
const config = {
feature: 'measure', // The Reach feature to load
authToken: 'jwt-token', // Initial JWT authentication token
// Optional theme customization
theme: {
styles: {
primary: '#00758a',
},
},
callbacks: {
onReauthRequested, // Function to handle token refresh
},
};
// Initialize SDK
const sdk = loadReachSDK(config);
In frameworks like React or Next.js, be careful not to initialize the SDK
multiple times. Store the instance in a ref or variable outside the
component’s render cycle.