How can I solve the problem of React login form status and browser auto-fill

When I stumbled upon a problem in a project, I had a form built with React and how the browser automatically interacted with it.

Did you know that because you have entered your username/password in the past, the browser will automatically enter it?

That is auto-fill, which is the cause of my problem. In particular, I copied it on Chrome and Firefox, but any browser may encounter this problem.

The form is usinguseStatehook.

This is an exampleemailFields of the table:

import { useState } from 'react'

//… const [email, setEmail] = useState(’’)

<input
id=‘email’
type=‘email’
name=‘email’ value={email} onChange={(event) => setEmail(event.target.value)} />

When you type an email in it,emailValue use updatesetEmailAnd it can be used in the form submission event, so it can be sent to the server.

At some point, I realized that the browser was auto-filling the email and password, but React couldn't recognize it!

Perhaps because it filled the field before React was fully operational, it was impossible to intercept the event.

I did some research and got lost in the inconsistencies of browsers and the differences in auto-fill functions, so I had to create a simple solution.

I did ituseRefwithuseEffect:

import { useState, useEffect, useRef } from 'react'

I create a reference:

const emailField = useRef(null)

And append it to the input field in JSX:

<input
  ref={emailField}
  id='email'
  type='email'                   
  name='email'
  value={email}
  onChange={(event) => setEmail(event.target.value)} 
/>

Then I added a piece of code to look up the value of the field every 100ms and callsetEmail()Update it:

useEffect(() => {
  let interval = setInterval(() => {
    if (emailField.current) {
      setEmail(emailField.current.value)
      //do the same for all autofilled fields
      clearInterval(interval)
    }
  }, 100)
})

This is not ideal. It involves DOM manipulation. When using libraries like React, we should avoid this kind of manipulation, but it can solve this problem.

What if there is no autofill? This will simply wait until the first character is typed, and then stop the loop.

Download mine for freeResponse Handbook


More response tutorials: