1- import React from 'react' ;
1+ import React , { useRef } from 'react' ;
22
33import loadHubspotScript from './loadHubspotScript' ;
44import { HubspotFormProps } from '../../models' ;
@@ -10,7 +10,8 @@ type HubspotFormContainerPropsKeys =
1010 | 'formInstanceId'
1111 | 'portalId'
1212 | 'region'
13- | 'formClassName' ;
13+ | 'formClassName'
14+ | 'createDOMElement' ;
1415
1516type HubspotFormContainerProps = Pick < HubspotFormProps , HubspotFormContainerPropsKeys > ;
1617
@@ -23,18 +24,25 @@ const HubspotFormContainer = (props: HubspotFormContainerProps) => {
2324 portalId,
2425 region,
2526 formClassName,
27+ createDOMElement,
2628 } = props ;
2729
30+ const containerRef = useRef < HTMLDivElement > ( null ) ;
31+ const hsContainerRef = useRef < HTMLDivElement > ( ) ;
32+
2833 const containerId = formInstanceId
2934 ? `hubspot-form-${ formId } -${ formInstanceId } `
3035 : `hubspot-form-${ formId } ` ;
3136
32- useMount ( ( ) => {
33- ( async ( ) => {
34- if ( ! window . hbspt ) {
35- await loadHubspotScript ( ) ;
36- }
37+ const createForm = ( ) => {
38+ if ( containerRef . current && ! hsContainerRef . current && createDOMElement ) {
39+ hsContainerRef . current = document . createElement ( 'div' ) ;
40+ containerRef . current . id = '' ;
41+ hsContainerRef . current . id = containerId ;
42+ containerRef . current . appendChild ( hsContainerRef . current ) ;
43+ }
3744
45+ if ( ! createDOMElement || hsContainerRef . current ) {
3846 if ( window . hbspt ) {
3947 window . hbspt . forms . create ( {
4048 region,
@@ -45,10 +53,26 @@ const HubspotFormContainer = (props: HubspotFormContainerProps) => {
4553 formInstanceId,
4654 } ) ;
4755 }
56+ }
57+ } ;
58+
59+ useMount ( ( ) => {
60+ ( async ( ) => {
61+ if ( ! window . hbspt ) {
62+ await loadHubspotScript ( ) ;
63+ }
64+
65+ createForm ( ) ;
4866 } ) ( ) ;
67+
68+ return ( ) => {
69+ if ( createDOMElement && containerRef . current && containerRef . current . lastChild ) {
70+ containerRef . current . removeChild ( containerRef . current . lastChild ) ;
71+ }
72+ } ;
4973 } ) ;
5074
51- return < div className = { className } id = { containerId } /> ;
75+ return < div className = { className } id = { containerId } ref = { containerRef } /> ;
5276} ;
5377
5478export default HubspotFormContainer ;
0 commit comments