Single Page Applications
View sample code and troubleshooting tips for integrating GrowSurf into common JavaScript frameworks such as React and Vue.
To test in a sandbox/development environment, we recommend creating two different campaigns for development and production environments. Learn more here.
Due to the asynchronous behavior of SPAs, if the GrowSurf Universal Code has already been added you may need to re-initialize GrowSurf at times. For example, if embeddable elements are not being displayed, call growsurf.init().
To initialize GrowSurf asynchronously within your SPA, simply include the following code within your React components
componentDidMount()
lifecycle event. IMPORTANT:
componentDidMount()
is a lifecycle method for class components and cannot be used in functional components. If you want to initialize GrowSurf using a functional component you will need to use the Effect Hook.This snippet of code will only add the GrowSurf Universal Code when a visitor is brought to a page within your site that includes the component with this code. Once the script has been added successfully and initialized, you will then have the ability to add any GrowSurf embeddable element(s) you would like within your components JSX.
App.js
class App extends React.Component {
componentDidMount() {
const script = document.createElement('script');
script.src = 'https://app.growsurf.com/growsurf.js?v=2.0.0';
script.setAttribute('grsf-campaign', 'jaoh4t');
script.async = true;
document.head.appendChild(script);
}
render() {
return (
<div>
<div className='App'>REACT + GROWSURF</div>
<div data-grsf-block-form></div>
</div>
)
}
}
App.js
import {useEffect} from 'react'
function App() {
// GrowSurf Universal Code
const addGrsfScript = () => {
const script = document.createElement('script');
script.src = 'https://app.growsurf.com/growsurf.js?v=2.0.0';
script.setAttribute('grsf-campaign', 'jaoh4t');
script.async = true;
document.head.appendChild(script);
};
useEffect(() => {
addGrsfScript();
}, [])
}
To access third-party javascript SDK's such as GrowSurf's JavaScript Web API from within Reacts Virtual DOM, you must use window(dot) syntax.
Example
window.growsurf.getParticipantId();
If you experience issues with embeddable elements rendering on the page (depending on how URL routes are handled in your SPA, this behavior will typically be seen when you refresh the webpage with the absolute route) you will need to call
growsurf.init()
to re-initialize GrowSurf to make the embeddable elements render.Last modified 9mo ago