alexgarces / react-typeform-embed

React wrapper for Typeform Embed SDK
https://alexgarces.github.io/react-typeform-embed/
MIT License
124 stars 35 forks source link

Example for React Functional Components #54

Closed rashad closed 3 years ago

rashad commented 3 years ago

Hello,

I'm fairly new to react and looking into embedding a form as a pop-up. I'm using functional components and can't really figure out how to adapt the classic example for functional stateless components (espacially the ref part). Any chance you can provide us with a working example ?

Cheers

lukasver commented 3 years ago

You could consider something like this:

import React, { useState, memo } from 'react';
import { ReactTypeformEmbed } from 'react-typeform-embed';
import PropTypes from 'prop-types'

const TYPEFORM_LINK = 'https://your.typeform.com/to/typeformId';

function Typeform({ options, children }) {
  const [typeformInnerRef, setTypeformInnerRef] = useState(null);

  const openForm = (typeformRef) => {
    if (typeformRef) {
      typeformRef.typeform.open();
    }
  }

  return (
    <>
      <ReactTypeformEmbed
        url={TYPEFORM_LINK)
        popup
        autoOpen={false}
        hideHeaders
        hideFooter
        buttonText='Contact'
        ref={(tf) => {
          setTypeformInnerRef(tf);
        }}
      />
      {
        children ||
        <button onClick={(e) => openForm(typeformInnerRef)}>
          Contactar
       </button>
      }
    </>
  )
}

export default memo(Typeform);

You can also change the useState for a useRef and inside the openForm function reference the ref.current to use the open and close methods of the ReactTypeformEmbed

Hope this helps!

alexgarces commented 3 years ago

Hello,

Sorry for the late reply.

The last version (1.0.1) is built using React components, so it should be much easier now. You can find some examples at the src/examples folder and at the README.

Cheers.