Integrating Typeform into Your Application: A Guide with Vanilla JavaScript, React, and Vue.js
Tags: react, vue, javascript, typeform
Published: 2024-03-17 09:26:55

Typeform provides a seamless way to create and embed interactive forms, surveys, quizzes, and more into your web applications. Whether you're building a personal website, a business portal, or an e-commerce platform, integrating Typeform can enhance user engagement and streamline data collection. In this guide, we'll explore how to add Typeform to your application using vanilla JavaScript, React, and Vue.js.

## Vanilla JavaScript Integration

First, let's start with a simple implementation using vanilla JavaScript. Below is a code snippet demonstrating how to dynamically load Typeform's embed script and initialize a slider popup when a button is clicked.

```
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div class="typeform-container"></div>
    <button id="startTfContainer">Start</button>
    <script src="index.js"></script>
</body>
</html>
```
When integrating Typeform into your web application, you might want to trigger the form's display as soon as your script loads. This is achievable by creating and opening a Typeform popover form. In your JavaScript file, you can implement this functionality with just a few lines of code.

```
// Define the showTF function
const showTF = () => {
  // Load Typeform embed.js script dynamically
  const script = document.createElement("script");
  script.src = "//embed.typeform.com/next/embed.js";
  script.async = true;
  document.head.appendChild(script);
  
  // Load Typeform slider CSS
  const cssLink = document.createElement("link");
  cssLink.setAttribute("rel", "stylesheet");
  cssLink.setAttribute("href", "embed.typeform.com/next/css/slider.css");
  document.head.appendChild(cssLink);

  // Wait for the script to load and then initialize the Typeform popup
script.onload = () => {
  const container = document.getElementById("typeform-container");
  const { open } = window.tf.createPopover("formId", {
    container,
    onReady: ({ formId }) => {
      console.log(`Form ${formId} is ready`);
      window.tf.load();
    }
  });
  open();
};

// Get the button element by its id
const startButton = document.getElementById("startTfContainer");

// Add an event listener to the button
startButton.addEventListener("click", showTF);

```

Following this, there are also events that we can utilize to enhance the interaction and functionality of our Typeform. Let's delve deeper into how we can handle these events to tailor the form behavior to our specific requirements.

```
const { close } = window.tf.createPopover("formId", {
  // Event handlers
  onQuestionChanged: ({ formId, ref }) => {
    console.log(`Question in form ${formId} changed to ${ref}`);
  },
  onHeightChanged: ({ formId, ref, height }) => {
    console.log(
      `Question ${ref} in form ${formId} has height ${height}px now`
    );
  },
  onSubmit: ({ formId, responseId }) => {
    console.log(`Form ${formId} submitted, response id: ${responseId}`);
    // Log a message 1500 milliseconds after form submission.
    setTimeout(() => {
      console.log("1500 milliseconds after form submission");
    }, 1500);
    // To retrieve the response, use `responseId` (you have to do it server-side)
    // More details: https://developer.typeform.com/responses/
  },
  onClose: (formId) => {
    console.log(`Modal window with form ${formId} was closed`);
  }
});
```

## React Integration

In a React application, you can create a reusable component to handle Typeform integration. Here's how you can achieve that:

```
const TfComponent = () => {
  const showTf = () => {
    // Similar code as vanilla JavaScript implementation
  };

  return (
    <>
      <div id="typeform-container"></div>
      <button id="startTfContainer" onClick={showTf}>
        Start
      </button>
    </>
  );
};

export default TfComponent;
```

## Vue.js Integration

Similarly, in a Vue.js application, you can create a component to integrate Typeform:

```
<template>
  <div id="app">
    <button @click="showTf">Show Typeform</button>
  </div>
</template>

<script>
export default {
  methods: {
    showTf() {
      // Similar code as vanilla JavaScript implementation
    }
  }
};
</script>

```

## Exploring Typeform Embed Options and Features

Now that we've covered the basics of integrating Typeform into our applications using vanilla JavaScript, let's explore the diverse range of embedding options and additional features that Typeform offers.
When we import the "//embed.typeform.com/next/css/slider.css" file, we're essentially importing the CSS file responsible for styling the slider component and defining how it will appear to the user. This is why we utilize the createSlider method on the window object:

```
window.tf.createSlider("formId", {
  container,
});
```

You have the flexibility to embed Typeform in a modal window, which is typically displayed over your website and is usually triggered by user actions such as clicking a button. There are several modal embed options provided by Typeform:

- Popup
- Slider
- Sidetab
- Popover

In addition to these modal embed options, Typeform provides us with some other useful features:

- **popover.css** and **createPopover**
- **sidetab.css** and **createSidetab**
- **slider.css** and **createSlider**
- **popup.css** and **createPopup**

These options allow for versatile integration of Typeform into your application, providing a seamless and interactive experience for your users. Whether you opt for a slider, popover, sidetab, or popup modal, Typeform offers the tools to enhance user engagement and streamline data collection within your web application.

## Customizing Typeform Integration: Styling and Container Control


Now that we've implemented the Typeform survey into our custom dialog, let's explore some further customization options. Typeform provides flexibility in styling, allowing us to integrate their forms seamlessly into our applications while maintaining our own design aesthetics.

For instance, we might have a specific layout requirement or prefer to use our own styling for the Typeform survey. In such cases, we can create a custom element on our webpage, such as a dialog, and apply the Typeform survey within it.

To ensure that the Typeform survey fits neatly into our custom dialog and adheres to our styling preferences, we need to apply the appropriate CSS classes. Also skip setting up css from 'embed.typeform.com'
Here's an example of how we can achieve this:

```
.typeform-container {
  height: inherit !important;
  width: inherit !important;
}

.tf-v1-widget,
.tf-v1-iframe-wrapper,
.tf-v1-popup,
iframe {
  height: inherit !important;
  width: inherit !important;
}
```

By applying the .typeform-container class to the specific element where we want to display the Typeform survey, we ensure that it maintains the correct dimensions within our custom dialog. Additionally, the CSS rules provided help handle the size of the components generated by Typeform, ensuring they inherit the dimensions of their parent container.

This level of customization allows us to seamlessly integrate Typeform surveys into our applications while maintaining control over their appearance and layout. Whether it's within a custom dialog, a dedicated section of a webpage, or any other element, Typeform's flexibility empowers us to create engaging user experiences that align with our design preferences.


Utilizing event listeners and configurations from window.tf.create, we can dynamically handle components, emit events, and ensure a seamless user experience. For example, by triggering this.$emit('close') on both onSubmit and onClose, or by accessing the close function during the unmounting lifecycle, we maintain control over the Typeform survey's behavior while enhancing its integration into our application.


## Considerations on NPM Package Installation

While there's an NPM package available for Typeform (@typeform/embed), it's essential to consider whether installing the package is necessary for your project. Depending on the level of integration and usage, you may opt for the lightweight approach demonstrated here. For a deeper exploration of when to consider installing the NPM package for Typeform integration, refer to [this article](https://dev.to/nebojsa91markovic/making-informed-decisions-when-to-utilize-npm-packages-in-frontend-development-43ik) for more insights.

Integrating Typeform into your application can enhance user interaction and streamline data collection. Whether you choose to implement it with vanilla JavaScript or leverage frameworks like React and Vue.js, the process remains straightforward and flexible.

Now that you have the tools at your disposal, go ahead and elevate your web applications with interactive Typeform forms!

## Conclusion:

Thank you for exploring the integration of Typeform into web applications with me. I encourage you to share your experiences, insights, and any questions you have about integrating Typeform into your projects in the comments section below.

If you're looking to further enhance your understanding or explore additional resources on Typeform integration, feel free to check out the official Typeform documentation or community forums.

Your engagement and contributions are greatly appreciated as we continue to learn and grow together in our development journey. Happy coding!