Autofill with React Hook Form, Yup, and MUI.

Autofill is an essential feature for web forms. It saves time and minimizes errors by automatically filling in previously entered data. However, certain things might not work when you use autofill in your forms, such as validation. In this article, I will provide a way to handle autofill using MUI, React Hook Form, and Yup, and to have it work even with autofill.

Background

At Trailhead, we have researched many different form libraries. We were inspired by Angular Reactive Forms (despite some of its drawbacks) and sought to find a similar package for React. React Hook Form turned out to be the closest to Angular Reactive Forms and, in some ways, even better. It is lightweight, flexible, and offers a simple and intuitive API.

One of its advantages is its validations resolver, which opens the way to validation libraries like Yup, kneel before Zod, Vest, and many others. Among these choices, we ultimately chose Yup because it offers a declarative API, supports schema validation, and has a wide range of validation methods for various data types, which helps build easy-to-read and maintainable validation schemas.

Below, I will show you how we overcame one key issue we encountered while integrating React Hook Form with Yup for validation and MUI as our UI component library. The issue was with autofill.

Autofill Issue with React Hook Form

One common issue with form autofill, especially in Chrome, is that form libraries, like React Hook Form, can only catch auto-filled values once the user interacts with the form, page, or console. Browsers do not propagate any events when auto-filling a form for security reasons. As a result, form libraries may be unable to validate or handle the auto-filled values properly.

Let’s Fix Autofill

First of all, we need to create the LoginForm component, which uses the useForm hook to set up the form with default values, and the TextField component from MUI for input fields.

import { TextField, Box } from '@mui/material';
import { useForm } from 'react-hook-form';

interface ICredentialsForm {
  username: string;
  password: string;
}

function LoginForm() {
  const {
    register,
  } = useForm<ICredentialsForm>({
    defaultValues: {
      username: '',
      password: '',
    },
  });

  return (
    <Box display="flex" flexDirection="column" gap="20px" maxWidth="200px">
      <TextField
        label="Username"
        variant="outlined"
        type="text"
        {...register('username')}
      />
      <TextField
        label="Password"
        variant="outlined"
        type="password"
        {...register('password')}
      />
    </Box>
  );
}

export default LoginForm;

Next, we need to add validations and the Login button. Since we decided to use the Yup library, let’s create a validation schema first.

import { object, string } from 'yup';

export const validationSchema = object().shape({
  username: string()
    .default('')
    .required(),
  password: string()
    .default('')
    .required(),
});

Now, we can add a resolver to the useForm hook and use formState for the Login button.

import { Button, TextField, Box } from '@mui/material';
import { useCallback } from 'react';
import { yupResolver } from '@hookform/resolvers/yup';
import { validationSchema } from './validation-schema';

function LoginForm() {
  const {
    register,
    formState: { isValid },
  } = useForm<ICredentialsForm>({
    resolver: yupResolver<ICredentialsForm>(validationSchema),
    defaultValues: {
      username: '',
      password: '',
    },
  });

  const login = useCallback(() => {
    // Login code
  }, []);

  return (
    <Box display="flex" flexDirection="column" gap="20px" maxWidth="200px">
      // ...
      <Button disabled={!isValid} variant="contained" onClick={login}>
        Login
      </Button>
    </Box>
  );
}

export default LoginForm;

Here’s a result we’ve get when we run this:

Notice, however, that the Login button is disabled because the browser expects user interactions to propagate the onChange event, which will update the form values. If we try to click on the disabled button, the browser will catch this interaction and trigger the onChange event first, and the form will get values just before the onClick event is triggered. While this works, it can be confusing for the user.

Let’s see what we can do to catch autofill and enable the Login button. There’s a way to detect autofill animation on the MUI Text Field. To do this, we must add the onAnimationStart property to the InputProps in TextField and catch even.animationName equals mui-auto-fill.

import { useCallback, AnimationEvent } from 'react';

function LoginForm() {
  //...

  const onUserNameAnimationStart = useCallback(
    () =>
      (event: AnimationEvent<HTMLDivElement>): void => {
        if (event.animationName === 'mui-auto-fill') {
          
        }
      },
    []
  );

  //...

  return (
    <Box display="flex" flexDirection="column" gap="20px" maxWidth="200px">
      <TextField
        label="Username"
        variant="outlined"
        type="text"
        InputProps={{
          onAnimationStart: onUserNameAnimationStart(),
        }}
        {...register('username')}
      />
      //...
    </Box>
  );
}

export default LoginForm;

We can do this only for the username because browsers allow us to keep the username empty but not the password.

Next, we need to add the extra form value autofilled, set it to true when the mui-auto-fill animation happens, and adjust the yup schema.

interface ICredentialsForm {
  username: string;
  password: string;
  autofilled: boolean;
}

const validationSchema = object().shape({
  username: string()
    .default('')
    .when('autofilled', ([autofilled], schema) => {
      return autofilled ? schema.notRequired() : schema.required('Required');
    }),
  password: string()
    .default('')
    .when('autofilled', ([autofilled], schema) => {
      return autofilled ? schema.notRequired() : schema.required('Required');
    }),
  autofilled: boolean().default(false),
});

function LoginForm() {
  const {
    register,
    setValue,
    formState: { isValid },
  } = useForm<ICredentialsForm>({
    resolver: yupResolver<ICredentialsForm>(validationSchema),
    defaultValues: {
      username: '',
      password: '',
      autofilled: false,
    },
  });

  const onUserNameAnimationStart = useCallback(
    () =>
      (event: AnimationEvent<HTMLDivElement>): void => {
        if (event.animationName === 'mui-auto-fill') {
          setValue('autofilled', true, { shouldValidate: true });
        }
      },
    []
  );

  //...

  return (
    //...
  );
}

export default LoginForm;

In the code above, we’ve used the when method from yup to make the username and password properties not required if autofilled equals true.

So, here’s the final result. As you can see, the Login button is enabled when the form is autofilled.

Bonus

To not let autofilled values break our validations, we need to clear it after any user interaction. To do so, we need to check if any field becomes dirty and set the autofilled property back to false:

import { useCallback, useEffect, AnimationEvent } from 'react';
//...

function LoginForm() {
  const {
    register,
    setValue,
    formState: { isValid, dirtyFields },
    watch,
  } = useForm<ICredentialsForm>({
    //...
  });

  const formValues = watch();

  //...

  useEffect(() => {
    if (Object.keys(dirtyFields).length > 0 && formValues.autofilled) {
      setValue('autofilled', false, { shouldValidate: true });
    }
  }, [formValues, dirtyFields, setValue]);

  return (
    //...
  );
}

export default LoginForm;

Conclusion

As you can see, handling autofill using React Hook Form, Yup, and MUI may be challenging, but investing just a little time into dealing with these edge cases can ultimately enhance the user experience for your application.

As always, Trailhead is available to help. You can contact us if you’d like help implementing this approach in your own React forms.

Picture of Maks Nechesonov

Maks Nechesonov

Maks is a highly experienced front-end developer with over nine years of experience in the industry. He has a strong background in creating responsive designs and web app development. He is passionate about delivering high-quality code, improving development processes, and always seeking ways to improve his skills. When not occupied with coding, Maks enjoys playing futsal, video games and board games, and spending time with his family.

Related Blog Posts

We hope you’ve found this to be helpful and are walking away with some new, useful insights. If you want to learn more, here are a couple of related articles that others also usually find to be interesting:

Our Gear Is Packed and We're Excited to Explore With You

Ready to come with us? 

Together, we can map your company’s software journey and start down the right trails. If you’re set to take the first step, simply fill out our contact form. We’ll be in touch quickly – and you’ll have a partner who is ready to help your company take the next step on its software journey. 

We can’t wait to hear from you! 

Main Contact

This field is for validation purposes and should be left unchanged.

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the form below. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Montage Portal

Montage Furniture Services provides furniture protection plans and claims processing services to a wide selection of furniture retailers and consumers.

Project Background

Montage was looking to build a new web portal for both Retailers and Consumers, which would integrate with Dynamics CRM and other legacy systems. The portal needed to be multi tenant and support branding and configuration for different Retailers. Trailhead architected the new Montage Platform, including the Portal and all of it’s back end integrations, did the UI/UX and then delivered the new system, along with enhancements to DevOps and processes.

Logistics

We’ve logged countless miles exploring the tech world. In doing so, we gained the experience that enables us to deliver your unique software and systems architecture needs. Our team of seasoned tech vets can provide you with:

Custom App and Software Development

We collaborate with you throughout the entire process because your customized tech should fit your needs, not just those of other clients.

Cloud and Mobile Applications

The modern world demands versatile technology, and this is exactly what your mobile and cloud-based apps will give you.

User Experience and Interface (UX/UI) Design

We want your end users to have optimal experiences with tech that is highly intuitive and responsive.

DevOps

This combination of Agile software development and IT operations provides you with high-quality software at reduced cost, time, and risk.

Trailhead stepped into a challenging project – building our new web architecture and redeveloping our portals at the same time the business was migrating from a legacy system to our new CRM solution. They were able to not only significantly improve our web development architecture but our development and deployment processes as well as the functionality and performance of our portals. The feedback from customers has been overwhelmingly positive. Trailhead has proven themselves to be a valuable partner.

– BOB DOERKSEN, Vice President of Technology Services
at Montage Furniture Services

Technologies Used

When you hit the trails, it is essential to bring appropriate gear. The same holds true for your digital technology needs. That’s why Trailhead builds custom solutions on trusted platforms like .NET, Angular, React, and Xamarin.

Expertise

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

  • Project Management
  • Architecture
  • Web App Development
  • Cloud Development
  • DevOps
  • Process Improvements
  • Legacy System Integration
  • UI Design
  • Manual QA
  • Back end/API/Database development

We partner with businesses who need intuitive custom software, responsive mobile applications, and advanced cloud technologies. And our extensive experience in the tech field allows us to help you map out the right path for all your digital technology needs.

Our Gear Is Packed and We're Excited to Explore with You

Ready to come with us? 

Together, we can map your company’s tech journey and start down the trails. If you’re set to take the first step, simply fill out the contact form. We’ll be in touch – and you’ll have a partner who cares about you and your company. 

We can’t wait to hear from you! 

Thank you for reaching out.

You’ll be getting an email from our team shortly. If you need immediate assistance, please call (616) 371-1037.