Update form created in React through VanillaJs

In this tutorial, we will learn how to populate the from created in React through vanillajs script.

Update form created in React through VanillaJs

Reactjs is one of the most popular frontend libraries at the moment and there are many applications that use it to create single-page applications as well as server-side rendered applications.

Recently, I was dealing with a problem where I had to populate the form fields such as Input, Checkbox, Radio-box, and Textarea using vanilla JavaScript.

When you try to populate the fields through a script, you can access the DOM elements and set their value, but if the application is listening to the event change to update values, you have to manually dispatch the events from your script by creating a new event, so that the event handler in the application can handle the event.

The form event such as click, change, and input can be dispatched from the script by creating a new event, this will work similarly to the original event fired by user action.

// access the form field
const emailAddress = document.getElementById("email-address");

// set it's value
emailAddress.value = "abc@learnersbucket.com";

// create a new event
const inputEvent = new Event("input", {
  bubbles: true,
});

// dispatch the event
emailAddress.dispatchEvent(inputEvent);

This works fine for applications that don’t explicitly maintain the state or have synthetic events.

In React, the library uses synthetic events, which helps to have a single event onChange that can be used on all form fields, rather than listening to the different events for different fields.

The synthetic events improve the developer experience as they don’t have to remember the particular event types for the form fields, but when you are trying to update the fields externally through a script, the normal events don’t trigger synthetic events.

That is because how synthetic events will work depends on their implementation in the library.

For example, on the Radiobox, the click event is dispatched, and then the input event is dispatched and then the change event, but even if you dispatch these the onChange event in React is never fired.

For React applications, you can use this library react-trigger-change that triggers all the events that synthetic events are listening to in React so that all the events in React are fired accordingly.

// load the react-trigger-change script
// you can load it in the HTML itself
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://unpkg.com/react-trigger-change/dist/react-trigger-change.js';
document.head.appendChild(script);

// get the radio button
const radios = document.querySelectorAll("input[type='radio']");

// check the radio with the value
radios.forEach((e) => {
  if (e.value === "option2") {
     e.checked = true;

     // trigger react change
     reactTriggerChange(e);
  }
});