I am trying to re-write my old JavaScript code and make it work for React.
The main idea behind this is just including some external data to my 3rd party form.
This is my old JS:
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js"></script>
<script>
hbspt.forms.create({
portalId: 'myID',
formId: 'myID',
onFormSubmit: function() {
jQuery('input[name="TICKET.content"]').val(JSON.stringify(window.cart,undefined, 2)).change();
}
});
</script>
And trying to make it work in React:
React.useEffect(() => {
const script = document.createElement('script');
script.src = 'https://js.hsforms.net/forms/v2.js';
document.body.appendChild(script);
script.addEventListener('load', () => {
if (window.hbspt) {
window.hbspt.forms.create({
portalId: 'myID',
formId: 'myID',
onFormSubmit: function() {
jQuery('input[name="TICKET.content"]').val(window.cart).change();
},
target: '#hubspotForm',
});
}
});
});
<div id="hubspotForm"></div>
Trying with react-hubspot-form
onSubmit={function (e) {
e.preventDefault();
const ticket = document.querySelector('input[name="TICKET.content"]');
const nativeInputValueSetter = Object.getOwnPropertyDescriptor( window.HTMLInputElement.prototype,'value').set;
nativeInputValueSetter.call(ticket, cart);
const evt = new Event('change', {bubbles: true,});
ticket.dispatchEvent(evt);}}
But with code above I am getting error of jQuery
is not being defined. Is there better way how to re-write or am I able to define jQuery somehow?