Как я могу встроить форму Typeform в свое приложение React?
Код внедрения, предоставляемый 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>





Вы можете просмотреть документацию Typeform для встраивания с помощью JavaScript здесь.
И их официальный модуль npm здесь.
Используйте 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;
Вы можете использовать созданный мной компонент-оболочку React: https://github.com/alexgarces/react-typeform-embed
Он использует официальный Typeform Embed SDK под капотом. В основном вам нужно передать URL-адрес вашей формы, но он также поддерживает другие параметры 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" />;
}
}
Это то, что я придумал для своего проекта, вдохновленный решением Элизы Чант и использующим компоненты на основе функций, хуки и 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' }}
/>
);
};
Я пробовал это и получаю сообщение об ошибке:
Could not find a declaration file for module 'react-typeform-embed'. 'xyz_path/node_modules/react-typeform-embed/lib/index.js' implicitly has an 'any' type.