Are there challenges and ways to handle errors with React Hook Form in Typescript?

Transitioning to React Hook Form from Formik while incorporating Material UI V5 and yup for validation poses a current challenge.

There are two key issues I am addressing:

  1. Encountering TS Errors related to various RHF props and options.
  2. Desiring validation on both onBlur and onSubmit, but currently only seeing HTML5 validation display onSubmit.

Below is the code snippet:

import { useForm, Controller } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import {
  Box,
  Button,
  CircularProgress,
  Grid,
  InputAdornment,
  TextField,
  Theme,
  Typography,
  useMediaQuery,
} from '@mui/material';
import { validationSchema } from './validationSchema'

const LoginForm: React.FC = () => {
  const {
    control,
    handleSubmit,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(validationSchema),
    mode: 'onBlur',
    reValidateMode: 'onChange',
    defaultValues: {
      email: '',
      password: '',
    },
  });

  const handleSignin = async (credentials: Values) => {
    // Logic for sign in here
  };

  return (
    <BoxContainer>
      <form onSubmit={handleSubmit(handleSignin)}>
        <Grid container spacing={2}>
          <Grid item xs={12}>
            <Controller
              name="email"
              control={control}
              render={({ field }) => (
                <TextField
                  {...field}
                  error={!!errors?.email}
                  helperText={errors?.email?.message}
                  size="small"
                  autoFocus
                  label="Email"
                  fullWidth
                  autoComplete="email"
                  type="email"
                  variant="outlined"
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <EmailIcon />
                      </InputAdornment>
                    ),
                  }}
                />
              )}
            />
          </Grid>
          // Other grid items and components...
        </Grid>
      </form>
    </BoxContainer>
  );
}

The flagged TS errors have been marked alongside the problematic code snippets.

The secondary issue arises when an invalid or empty email input transitions between focus states resulting in differing error feedback. Ideally, I aim for combined onBlur and onSubmit validation modes.

Thus far, React Hook Form exhibits promise, with ongoing refinement of errors and functionality.

Answer №1

It appears that your initial problem may be related to an ongoing issue on Github which you can find more information about here. Fortunately, there is a workaround shared in this Stack Overflow response.

To address the second issue, ensure you include the noValidate attribute within the <form /> element and allow RHF to handle the validation process seamlessly.

<form onSubmit={handleSubmit(handleSignin)} noValidate>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for integrating a tensorflow.js model into a React-based web application?

I've been working on a React web application in Typescript that involves loading a tensorflow.js model and then applying it each time the component updates. While I successfully implemented this in a small demo app without React, I am facing some chal ...

Adding an icon to the Autocomplete TextField in MUI v5 in Reactjs: A step-by-step guide

I created an autocomplete feature with the code below and attempted to display an icon after selecting each item, but unfortunately, it didn't work as expected! import { useState } from 'react' import { TextField,InputAdornment ,Autocomplete ...

Loading dynamic content within Angular Material tabs allows for a more customized and interactive user experience

I am currently working on creating a dynamic tab system using Angular Material: Tabs. I have encountered an issue with loading content on tabs after the initial one, where the functionality only works when the first tab is loaded. Below you can see the ta ...

Error in TypeScript while running the command "tsd install jquery" - the identifier "document" could not be found

Currently, I am facing an issue with importing jQuery into my TypeScript project. In order to achieve this, I executed the command tsd install jquery --save, which generated a jquery.d.ts file and added /// <reference path="jquery/jquery.d.ts" /> to ...

Utilizing AWS Websockets with lambda triggers to bypass incoming messages and instead resend the most recent message received

I am facing an issue when invoking a lambda that sends data to clients through the websocket API. Instead of sending the actual message or payload, it only sends the last received message. For example: Lambda 1 triggers Lambda 2 with the payload "test1" ...

The MUI static datepicker sx property is malfunctioning

I am trying to deactivate the default action buttons in the mui datepicker by using the sx props, but for some reason it's not working properly This is the code I have implemented for the datepicker component: <LocalizationProvider dateAdapter={Ad ...

Guide to transforming JSON data into a different structure

My API is currently providing data in this format: [ { "lattitude": 52.57812538272844, "longitude": -1.7111388218750108, }, { "lattitude": 53.043884, "longitude": -2.923782, } ] I need to transform the data ...

404 Error: Unable to Locate Socket Io

I'm currently working on implementing a chat feature in Angular 2 using Socket IO, following this tutorial. However, I encountered an error message during a test on the server: GET http://localhost:3000/socket.io/?EIO=3&transport=polling& ...

Error: Certain Prisma model mappings are not being generated

In my schema.prisma file, I have noticed that some models are not generating their @@map for use in the client. model ContentFilter { id Int @id @default(autoincrement()) blurriness Float? @default(0.3) adult ...

Ways to sort mat-select in alphabetical order with conditional names in options

I am looking to alphabetically order a mat-select element in my Angular project. <mat-select [(ngModel)]="item" name="item" (selectionChange)="changeIdentificationOptions($event)"> <mat-option *ngFor="let item of items" [value]="item"> ...

Accessing external data in Angular outside of a subscription method for an observable

I am struggling to access data outside of my method using .subscribe This is the Service code that is functioning correctly: getSessionTracker(): Observable<ISessionTracker[]> { return this.http.get(this._url) .map((res: Response) => ...

Modifying the Placeholder Color in a Material UI Autocomplete: Tips and Tricks

In my team, we are working on two projects that both utilize an internal library with a header containing a search box. In one project, the placeholder text "Search" displays normally. https://i.stack.imgur.com/lhL5V.png However, in the second project wh ...

Navigating to a new page by selecting a row in a material-ui table

Within my project, there is a file labeled route-names.js containing the following entry: export const REVIEW_FORM_URL = '/custom-forms/:customFormId'; In one of my material-ui tables with multiple rows, clicking on a row reveals the id as ...

Is it possible in Angular to directly bind the emitted output of a component to a property?

My primary application component communicates with its sub components using @Output decorated properties on the subcomponent. The output properties utilize an EventEmitter<>(). Typically, these properties emit a simple boolean or number. I want to di ...

What is the best way to generate a dummy ExecutionContext for testing the CanActivate function in unit testing?

In my authGuard service, I have a canActivate function with the following signature: export interface ExecutionContext extends ArgumentsHost { /** * Returns the *type* of the controller class which the current handler belongs to. */ get ...

I am having trouble getting ngFor to properly render my accessible data. Whenever I attempt to use it, it ends up breaking my code. Can someone please

When using *ngFor to iterate through data, everything appears to be working fine until attempting to access nested data within an object inside another object. For example: { "tvshow": [ { "id": "value", "time": { "clock": "valu ...

flushMicrotasks does not function properly in conjunction with the image.onload event

Working on an Angular project, I'm currently developing an object with an image field. The method responsible for loading the image returns a promise that resolves in the onload function of the image. When trying to test this method using the flushMi ...

Enhance your data grid experience with React Mui's expandable rows feature, allowing for easy reset of models from the

My data grid component, DataGridPro, has the following parameters: <DataGridPro apiRef={apiRef} density="comfortable" autoHeight headerHeight={75} getRowId={(row) => row.domain_id} loading={ta ...

"I am facing issues with Nodejs $lookup as it is not producing the

I am looking to merge two document collections. The first collection, "prefix," contains an array of category IDs under the categoryId key, while the second collection, "categories," holds objects with a unique _id field. Here is my sample database structu ...

Invoking a React function repeatedly (every second)

Currently, I am working with React and utilizing Material UI to create a modal. The modal is rendered as part of the body of the code, placed at the bottom of the page. Its visibility is controlled by the state; if it's open or closed. However, I&apos ...