Stefan Guggisberg
Stefan Guggisberg

Reputation: 143

Populate state with values from autocomplete (react)

I have a component with inputfields and a button which is disabled unless the correct values are entered in the inputfields. This works fine but when chrome autocompletes those values on page load, the state isn't changed and thus the button stays disabled. If you click inside the form or change a value the state changes correctly.

How can I get the value from autocomplete when the component load? Autocomplete doesn't trigger the onChange or onBlur events and autocomplete="off" doesn't work either. (also I'd prefer not to turn off autocomplete anyways)

Upvotes: 3

Views: 3786

Answers (1)

cdpautsch
cdpautsch

Reputation: 2003

I recently came across this problem while working on my login page. After a bit of research, I came across this issue reported on the ReactJS github. To quote the key part:

If we are able to access autofilled values once the page loads, it would become very easy to write malicious code to extract information on a form intended for phishing. Giving the user no chance to react. Probably part of the reason why autocomplete="off" is ignored by browsers.

To overcome this problem we need to:

  1. Accept the fact that we won't (and never will) have access to autofilled values when the DOM node mounts
  2. Embrace the security concerns which are brought up by the browsers

tl;dr - It's intentional for security reasons, and it's better to validate the inputs upon submit instead.

Upvotes: 2

Related Questions