Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass onBlur and sx props in slotsProp of MUI DatePicker 6

I have this DatePicker component using MUI DatePicker v6.

/* eslint-disable no-unused-vars */
// @ts-nocheck
import * as React from 'react';
import { Controller } from 'react-hook-form';
import TextField from '@mui/material/TextField';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import './common.css';
import { DatePicker, LocalizationProvider } from '@mui/x-date-pickers';
export const CustomDatePicker = (props) => {
  const { control, name, label } = props;
  const [error, setError] = React.useState(null);
  return (
    <Controller
      name={name}
      control={control}
      render={({ field: { onChange, value, ref }, fieldState: { error } }) => (
        <LocalizationProvider dateAdapter={AdapterDayjs}>
          <DatePicker
            size="small"
            name={name}
            label={label}
            control={control}
            format="DD-MMM-YYYY"
            value={value}
            onChange={(event) => {
              onChange(event);
            }}
            disableFuture
            sx={{ width: props.width ?? 250 }}
            InputProps={{
              style: {
                padding: 8
              }
            }}
            disableMaskedInput
            slotProps={{
              textField: {
                helperText: error?.message,
                error: error?.message ? true : false,
                size: 'small',
                readOnly: true
                //add sx here
                //add onBlur here
              }
            }}
          />
        </LocalizationProvider>
      )}
    />
  );
};
export default CustomDatePicker;

I want to set an onBlur and sx props on generated TextField component but don't know the correct format when props are set as JSON object. Cannot find any example in the documentation too.

like image 725
NothingBox Avatar asked Sep 12 '25 06:09

NothingBox


1 Answers

the correct format for setting the onBlur and sx props on the generated TextField component

<DatePicker 
   format="DD-MMM-YYYY"
   onChange={(event) => {
     console.log('Input blurred. Value:');
   }}
   disableFuture
   sx={{ width:  250 }}
   slotProps={{
     textField: {

       sx: {
         backgroundColor: 'lightgray',
         borderRadius: 4,
         '& input': {
           backgroundColor: 'green',
         },
       },
       onBlur: (event) => {
         console.log('Input blurred. Value:', event.target.value);
       }
     }
   }}
  />

you can view here in codesandbox

like image 99
Muhammad Idrees Avatar answered Sep 14 '25 20:09

Muhammad Idrees