Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty password input value on autocomplete (React.js)

After my login form is autocompleted by the browser, the queried password input's value is empty. After I click into the password field, the value gets magically available, also there are many events fired by the browser that don't make sense. (The onChange on password input is not among them.)

  • Why is the value on input[type=password] empty?
  • Why the autocomplete on password input doesn't fire onChange event?
    ( it fires on normal input )
  • Bonus question: Why there is the second (unnecessary) focus/blur event?

1. Both inputs set to type="text"

  • Both inputs get rendered once (no autocomplete)

console1

note: My inputs are uncontrolled but stateful and I track state changes on focus, blur, change

  • entered=true when there is a value entered
  • focused=true when onFocus fired, =false when onBlur fired
  • peek=true when I need to programatically force type from password to text

2. Input set to type="password"

(See how the form is autocompleted.)

form

console2

  • ...

  • 2.render (red arrow) - Browser focused the input

  • onChange fired on email input

  • 3.render - Internal state changed (entered=true)

  • 4.render - Browser unfocused the input

  • 5.render (yellow arrow) - Browser focused the input again?

  • 6.render - Browser unfocused the input
    Browser didn't make any changes to dom element

  • preview password - changed input type to text programatically

  • manual validateForm() - password is empty, form is invalid

  • manual interaction also says the value is "" empty

What is interesting is that after pressing the PrtScr in the browser, the value gets available and form gets rerendered - as when focusing the input by hand.

like image 269
Qwerty Avatar asked Nov 07 '22 16:11

Qwerty


1 Answers

An issue on the React GitHub discussing this: https://github.com/facebook/react/issues/1159. Spoiler: it's been active since Feb 2014 with no resolution.

Possible workaround: making a custom change handler that listens to the native browser event instead of the react synthetic one. This is complicated by the fact that we're using custom input elements from our validation library instead of native inputs which I'm sure to have their own change handlers to re-validate and we don't want to break those

Another possible workaround: save refs to all the form fields and manually grab their .value before submitting rather than relying on the managed values in the state, which is decidedly non-reactive and definitely not ideal

like image 58
Matthew Benjamin Avatar answered Nov 14 '22 21:11

Matthew Benjamin