Fastlane Deferred Form Submissions with React

Overview

Because of React component's Lifecycle, it can be tricky to load and trigger the correct scripts to launch a Fastlane Playbook. In order to make it work correctly, we need to make sure we are adding the correct scripts to the page <body> at the right time.

Implementation

First, we need to stage the form data when it is submitted. This is done by triggering Drift API method stageFormData. We need to make sure to add this script in our React Form component once the component mounts, using componentDidMount().

componentDidMount() {
    const script = document.createElement("script");
    const scriptText = document.createTextNode(
      "var myform = document.querySelector('form');if(myform) {myform.addEventListener('submit', function (event) { console.log('submit'); var form = event.target; drift.api.stageFormData(form)})}");
    script.appendChild(scriptText);
    document.body.appendChild(script);
}

Once we stage the form data, we will need to commit it. This is the script that will open the Fastlane playbook. In this case, we want to trigger the Fastlane Playbook from the Thank you React component. So, we need to add the commit script in the Thank you component componentDidMount() method

componentDidMount() {
    const script = document.createElement("script");
    const scriptText = document.createTextNode(
      "drift.on('ready', function (api) { api.commitFormData({ campaignId: 0000000 // update me with the playbook's campaign id!});});"
    );
    script.appendChild(scriptText);
    document.body.appendChild(script);
}

📘

componentDidMount()

Adding Drift API scripts inside the componentDidMount() function, will ensure that the scripts are loaded and triggered whenever the DOM is ready to be used.


Did this page help you?