Unable to display helper text in MUI date picker when using along with react-hook-form library

I've used react-hook-form library along with material-ui. I've been trying display a mandatory field error message for the date picker through the helper text attribute of MUI but unable to display it. I'm getting the error messages for the text fields within the same form. And it even gets logged in the console. But I'm not able to render it. I believe it has something to do with the implementation of the date of birth controller component.

Date picker not displaying the error message

import React from "react";
import { useForm, Controller } from "react-hook-form";
import TextField from "@mui/material/TextField";
import DatePicker from "@mui/lab/DatePicker";
import AdapterDateFns from "@mui/lab/AdapterDateFns";
import LocalizationProvider from "@mui/lab/LocalizationProvider";

export default function NewCandidateForm() {
  const {
    handleSubmit,
    formState: { errors },
    control,
  } = useForm();
  const onSubmit = (data) => console.log(data);
  console.log(errors);

  return (
    <form
      onSubmit={handleSubmit(onSubmit)}
      style={{
        display: "flex",
        flexDirection: "column",
        width: "300px",
        rowGap: "20px",
      }}
    >
      <Controller
        name="firstName"
        control={control}
        defaultValue=""
        render={({ field: { onChange, value }, fieldState: { error } }) => (
          <TextField
            label="First Name"
            variant="filled"
            value={value}
            onChange={onChange}
            error={!!error}
            helperText={error ? error.message : null}
          />
        )}
        rules={{ required: "First name required" }}
      />

      <Controller
        name="lastName"
        control={control}
        defaultValue=""
        render={({ field: { onChange, value }, fieldState: { error } }) => (
          <TextField
            label="Last Name"
            variant="filled"
            value={value}
            onChange={onChange}
            error={!!error}
            helperText={error ? error.message : null}
          />
        )}
        rules={{ required: "Last name required" }}
      />

      <Controller
        name="dob"
        control={control}
        defaultValue=""
        render={({ field: { onChange, value }, fieldState: { error } }) => (
          <LocalizationProvider dateAdapter={AdapterDateFns}>
            <DatePicker
              label="Date of Birth"
              value={value}
              onChange={onChange}
              renderInput={(error) => (
                <TextField
                  {...error}
                  helperText={error ? error.message : null}
                />
              )}
              style={{
                paddingBottom: "10px",
                paddingTop: "10px",
                color: "white",
              }}
            />
          </LocalizationProvider>
        )}
        rules={{ required: "Date of birth required" }}
      />

      <Controller
        name="mobile"
        control={control}
        defaultValue=""
        render={({ field: { onChange, value }, fieldState: { error } }) => (
          <TextField
            label="Mobile"
            variant="filled"
            value={value}
            onChange={onChange}
            error={!!error}
            helperText={error ? error.message : null}
          />
        )}
        rules={{ required: "Mobile number required" }}
      />

      <input
        variant="contained"
        style={{
          height: "40px",
          width: "200px",
          alignItems: "center",
          marginTop: "20px",
          border: "hidden",
          borderRadius: "25px",
        }}
        type="submit"
      />
    </form>
  );
}

Also, another issue that I've been facing is that upon the first or the initial render or loading of the page, the date picker field appears in red color which symbolises like an error.

Initial load/render of the page where date picker is red in color

Upvotes: 4

Views: 10023

Answers (2)

Shafayet Haydar
Shafayet Haydar

Reputation: 71

Problem-1: To show helper text, you can do this using slotProps:

<DatePicker
  label={label}
  name={name}
  value={value}
  autoFocus={autoFocus}
  onChange={onChange}
  format="YYYY-MM-DD"
  closeOnSelect
  className={`${className}`}
  slotProps={{
    textField: {
      error: error, // Bolean
      helperText: helperText, // String
    },
  }}
/>

Problem-2: Your date value is not in correct format. You have to provide the correct date value.

Upvotes: 5

YESID SANCHEZ RAMOS
YESID SANCHEZ RAMOS

Reputation: 56

try this

// component FormDatePicker

export interface FormDatePickerProps {
  name: string;
  label: string;
  control: any;
  defaultValue?: any;

}

function FormDatePicker({
  name,
  label,
  control,
  defaultValue,
}: FormDatePickerProps) {
  return (
    <Controller
      control={control}
      name={name}
      defaultValue={defaultValue ?? null}
      render={({ field: { onChange, value, ref }, fieldState }) => (
        <LocalizationProvider dateAdapter={AdapterDateFns}>
          <DatePicker
            onChange={onChange}
            value={value}
            label={label}
            ref={ref}
            
            renderInput={(params) => (
              <TextField
                sx={{ width: '100%' }}
                {...params}
                error={Boolean(fieldState.error)}
                helperText={fieldState?.error?.message}
              />
            )}
          />
        </LocalizationProvider>
      )}
    />
  );
}

export default FormDatePicker;

you use it like this

 <FormDatePicker
    name="birthdayDate"
    label="date"
    control={control}
    defaultValue={null}
/>

Upvotes: 4

Related Questions