Prefill a HubSpot Form in a React App

I have a React App with a HubSpot contact form. The user must be logged into submit the form so I wanted to prefill their email address.

Fortunately, HubSpot Forms API provides a onFormReady callback!

Code Sample

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const HubSpotContactForm = () => {
const { getClaims } = useAmplify();
const [email, setEmail] = useState<string>('');

useEffect(() => {
getClaims().then((d) => setEmail(d?.email));
}, []);

useEffect(() => {
if (email) {
const script = document.createElement('script');
script.src = 'https://js.hsforms.net/forms/v2.js';
document.body.appendChild(script);

script.addEventListener('load', () => {
const hbspt = (window as any).hbspt;
if (hbspt) {
hbspt.forms.create({
portalId: 'TODO',
formId: 'TODO',
target: '#hubspotForm',
onFormReady: function ($form: any) {
const emailInput = $form[0];
emailInput.value = email;
emailInput.dispatchEvent(new Event('input', { bubbles: true }));
},
});
}
});
}
}, [email]);

return (
<Container
header={
<Header
variant="h2"
description="Submit any questions or feedback here and we will get back to you shortly"
>
Contact Form
</Header>
}
>
<div id="hubspotForm"></div>
</Container>
);
};
Share