How to programmatically fill input elements built with React?

Timo Kauranen picture Timo Kauranen · Nov 30, 2016 · Viewed 11.8k times · Source

I'm tasked with crawling website built with React. I'm trying to fill in input fields and submitting the form using javascript injects to the page (either selenium or webview in mobile). This works like a charm on every other site + technology but React seems to be a real pain.

so here is a sample code

var email = document.getElementById( 'email' );
email.value = '[email protected]';

I the value changes on the DOM input element, but the React does not trigger the change event.

I've been trying plethora of different ways to get the React to update the state.

var event = new Event('change', { bubbles: true });
email.dispatchEvent( event );

no avail

var event = new Event('input', { bubbles: true });
email.dispatchEvent( event );

not working

email.onChange( event );

not working

I cannot believe interacting with React has been made so difficult. I would greatly appreciate any help.

Thank you

Answer

meriial picture meriial · Dec 15, 2018

This accepted solution appears not to work in React > 15.6 (including React 16) as a result of changes to de-dupe input and change events.

You can see the React discussion here: https://github.com/facebook/react/issues/10135

And the suggested workaround here: https://github.com/facebook/react/issues/10135#issuecomment-314441175

Reproduced here for convenience:

Instead of

input.value = 'foo';
input.dispatchEvent(new Event('input', {bubbles: true}));

You would use

function setNativeValue(element, value) {
  const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set;
  const prototype = Object.getPrototypeOf(element);
  const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;

  if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(element, value);
  } else {
    valueSetter.call(element, value);
  }
}

and then

setNativeValue(input, 'foo');
input.dispatchEvent(new Event('input', { bubbles: true }));