'unable to show error and error message on MUI datepicker

I'm using react material-ui (MUI)

I want to show an error on some condition that will calculate on the backend.

I used MUI-datepicker but I can't show error

import * as React from 'react';
import TextField from '@mui/material/TextField';
import AdapterDateFns from '@mui/lab/AdapterDateFns';
import LocalizationProvider from '@mui/lab/LocalizationProvider';
import DatePicker from '@mui/lab/DatePicker';

const PickupDatePickerComponent = (props) => {

  const [value, setValue] = React.useState(null);

  const handleChange = (newValue)=>{
    setValue(newValue);
  }

  const todayDate = new Date();

  return (
    <LocalizationProvider style={{ width:"100%"}} dateAdapter={AdapterDateFns}>
      <DatePicker
        label="example"
        value={value}
        onChange={handleChange}
        minDate={todayDate}
        renderInput={(params) => <TextField 
          error
          helperText="Your error message" 
          {...params} sx={{ width:"100%" }} 
        />}
        onError={true}
        error
        helperText="Your error message"
      />
    </LocalizationProvider>
  );
}

export default PickupDatePickerComponent

the error property is not working not in <Input/> nor in <DatePicker/> so the border won't be red... (like normal errors)



Solution 1:[1]

Put error attribute after {...params} sx={{ width:"100%" }}
like this

renderInput={(params) => <TextField 
      
      {...params} sx={{ width:"100%" }} 
      error
      helperText="Your error message" 
    />}

Solution 2:[2]

The DatePicker spreads props through to children elements, so you can in fact use the errorText and errorStyle props from the TextField element. For example, I tested the following DatePicker in "^0.18.7" and can confirm it shows up with a red error message:

<DatePicker hintText="Portrait Dialog" errorText="This is an error message." />

You should be aware that the onChange callback in the DatePicker is only fired when a date is selected, so the date argument will never be null or undefined. In other words, you'll never enter into the following if statement:

if(date == null || date == undefined){
  this.setState({
    dobError: 'Please select your date of birth'
  });
}

If you want to check for cases in which the user has not set any kind of date, consider just checking whether or not your DOB is null (I left out the irrelevant props to keep things short):

<DatePicker 
    errorText={this.state.dob ? {} : this.state.dobError} 
    errorStyle={this.state.dob ? {} : errorStyle} 
 >

Solution 3:[3]

i passed to onError prop a callback function as recommended in docs , this is a working demo based on your code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tâm Tr?n
Solution 2 Eduard
Solution 3 misterM