在React app中嵌入Typeform

时间:2018-06-08 22:29:01

标签: reactjs typeform

如何在我的React应用程序中嵌入Typeform表单?

Typeform提供的嵌入代码不能在JSX中编译。

这是嵌入代码的示例:

<div class="typeform-widget" data-url="https://sample.typeform.com/to/32423" style="width: 100%; height: 500px;"></div> <script> (function() { var qs,js,q,s,d=document, gi=d.getElementById, ce=d.createElement, gt=d.getElementsByTagName, id="typef_orm", b="https://embed.typeform.com/"; if(!gi.call(d,id)) { js=ce.call(d,"script"); js.id=id; js.src=b+"embed.js"; q=gt.call(d,"script")[0]; q.parentNode.insertBefore(js,q) } })() </script> <div style="font-family: Sans-Serif;font-size: 12px;color: #999;opacity: 0.5; padding-top: 5px;"> powered by <a href="https://admin.typeform.com/signup?utm_campaign=ezQ2ub&utm_source=typeform.com-12183356-Basic&utm_medium=typeform&utm_content=typeform-embedded-poweredbytypeform&utm_term=EN" style="color: #999" target="_blank">Typeform</a> </div>

4 个答案:

答案 0 :(得分:2)

您可以使用我创建的React包装器组件:https://github.com/alexgarces/react-typeform-embed

它使用引擎盖下的官方Typeform Embed SDK。基本上,您必须传递表单网址,但它还支持其他SDK选项。

import React from 'react';
import { ReactTypeformEmbed } from 'react-typeform-embed';

class App extends React.Component {
  render() {
    return <ReactTypeformEmbed url="https://demo.typeform.com/to/njdbt5" />;
  }
}

答案 1 :(得分:1)

您可以使用JavaScript here查看用于嵌入的Typeform文档。

他们的官方npm模块here

使用React refs触发初始化,类似于初始化jQuery插件的方式。

import React from 'react';
import * as typeformEmbed from '@typeform/embed'

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.el = null;
  }
  componentDidMount() {
    if (this.el) {
      typeformEmbed.makeWidget(this.el, "https://sample.typeform.com/to/32423", {
        hideFooter: true,
        hideHeaders: true,
        opacity: 0
      });
    }
  }
  render() {
    return (
      <div ref={(el) => this.el = el} style={{width: '100%', height: '300px'}} />
    )
  }
}

export default Form;

答案 2 :(得分:0)

受到 Elise Chant 解决方案的启发,并使用基于函数的组件、钩子和 Typescript,这就是我为我的项目想到的。我不想在官方 SDK 之上安装另一个瘦包装器。

import * as typeformEmbed from '@typeform/embed';
import React, { useEffect, useRef } from 'react';

interface EmbeddedTypeformProps {
  link: string;
  hideFooter?: boolean;
  hideHeaders?: boolean;
  opacity?: number;
}

export const EmbeddedTypeform: React.FunctionComponent<EmbeddedTypeformProps> = ({
  link,
  hideFooter = true,
  hideHeaders = true,
  opacity = 90,
}) => {
  const elementRef = useRef(null);

  useEffect(() => {
    typeformEmbed.makeWidget(elementRef.current, link, {
      hideFooter,
      hideHeaders,
      opacity,
    });
  }, [link]);

  return (
    <div
      ref={elementRef}
      style={{ width: '100%', height: '100%', flex: '1 1 auto' }}
    />
  );
};

答案 3 :(得分:0)

如果您在 React 中使用 Typescript 并且遇到此错误,只需确保 noImplicitAny 文件中的 tsconfig 设置为 false: "noImplicitAny": false,

相关问题