Can you provide information on the type signature of the `onChange` event for the MUI DatePicker?

I am utilizing an instance of the MUI DatePicker along with a MomentAdapter:

import *, {useState} as React from 'react';
import TextField from '@mui/material/TextField';
import { AdapterMoment } from '@mui/x-date-pickers/AdapterMoment';

import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { Moment } from 'moment';

function App() {

  const [value, setValue] = useState<Moment | null>();

  return (
    <LocalizationProvider dateAdapter={AdapterMoment}>
      <DatePicker
        value={value}
        onChange={(date: Moment | null) => {
          setValue(date);
          console.log(date);
        }}
        renderInput={(params) => <TextField {...params} />}
      />
    </LocalizationProvider>
  )
}

The content of date appears to be a type of Moment object, evident through inspection in the console:

https://i.sstatic.net/ZXqE5.png

However, TypeScript is flagging an error as it expects a Date object instead.

(Interestingly, there are discrepancies when testing this code sourced from MUI documentation on a StackBlitz, where the value does appear to be a date. The issue is compounded by the fact that the StackBlitz console doesn't display objects effectively.)

What should be the appropriate type signature for the function onChange in this scenario?

Answer №1

The onChange attribute can be found within the

UsePickerValueBaseProps<TValue, TError>
interface and is described as follows:

onChange?: (value: TValue, context: PickerChangeHandlerContext<TError>) => void;

The TValue parameter is derived from the DatePicker component itself, allowing you to define it within the component for proper typing of the onChange method:

<DatePicker<Moment>
  onChange={(date: Moment | null) => {
    setValue(date);
    console.log(date);
  }}
/>

If not specified, an error will occur because TValue defaults to type Date.

Answer №2

It's evident that the date variable holds a Moment object, as I confirmed by inspecting it in the console.

Keep in mind that when you set the value to a Moment object yourself, the internal type used by the component may not match the type you are providing. The console.log(value) statement checks the type of your value variable, not the new date being passed in by the component.

Your onChange method should look something like this:

onChange={(date: Date | null) => {
          setValue(date);
          console.log(`${date} has type ${typeof date}`);
        }}

If you update it as shown above, check if it now displays a Date type.

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

How to Incorporate Custom Colors into Material UI Themes

I'm currently working on developing a unique theme with custom colors using Material UI in React. The issue I am facing is that while I can successfully create the custom theme and view it in the console with the new color values, I encounter an error ...

Implementing a gradient on the background of Material UI's theme

I am attempting to customize the default background color of the MuiTheme by using a gradient effect. The code I currently have is as follows: export const theme = createMuiTheme({ palette: { type: "dark", background: { default: & ...

Consolidating Typescript modules into a single .js file

Recently, I was able to get my hands on a TypeScript library that I found on GitHub. As I started exploring it, I noticed that there were quite a few dependencies on other npm packages. This got me thinking - is there a way to compile all these files int ...

Using `querySelector` in TypeScript with Vue 3

Encountered a TypeScript error while using the Vue Composition API let myElement = document.querySelectorAll('my-element') The TS error I'm getting when trying to access it like this: Property '_props' does not exist on type ...

Angular background image not displayed

After searching extensively, I came across many examples that didn't work for me. I'm not sure what I'm doing wrong and I need assistance! I noticed that I can see the image if I use the <img> tag, but not when I try to set it as a ba ...

Is it possible to automatically switch to a different route in a Next.js server component after a certain period of time?

Is it possible to achieve a similar function in an async server component: displaying the ui, waiting 3 seconds, and then redirecting to another route? In a client component, you can accomplish this using: useEffect(() => { function delay(ms: number) ...

Managing font size in Material UI - Adjusting label text size in FormControlLabel

Is it possible to customize the font size of the label within FormControlLabel while utilizing React for Front End JS development? <FormGroup row> <FormControlLabel control={ <Checkbox onClick={() => onClick('r ...

Switching from a Promise to an Observable using React-Redux and TypeScript

I am struggling to grasp the concept of storing a Promise response into Redux. I believe finding a solution to this issue would greatly benefit me. Currently, I am utilizing a library that returns a Promise, and I wish to save this response - whether it i ...

Navigating the pathway to retrieving variables within an Angular Component function

export class MapsComponent implements OnInit { @ViewChild('googleMap') gmapElement: any; map: google.maps.Map; data = "initialised"; ngOnInit() { var directionsService = new google.maps.DirectionsService; ...

retrieve a shared string from an array when toggled

Regarding the use of SelectionModel for mat-checkbox, a function is called on each click: toggleSelection(row) { this.selection.toggle(row); console.log("Selection"); console.log("this", this.selection.selected); this.selection.selected.f ...

Stop the inheritance of static components in a feature module by protecting the router-outlet

I am in the process of dividing my app into multiple feature modules. Currently, I am using only the router-outlet inside a component within a feature module. However, this approach brings along all the static components such as the navbar and footer. How ...

When encountering the error message "Warning Invalid prop `color` with value `inherit` given to `ForwardRef(TextField)`, make sure to provide either "primary" or "secondary" as valid options

Recently, I encountered this warning message: Warning: Failed prop type: The prop color value of inherit is invalid for the component ForwardRef(TextField). It should be either primary or secondary. To address this issue, I attempted changing the color f ...

How can I dynamically insert a new HTML element into $event.target using Angular 2?

I have a webpage with a list of items. I want to display a "copy" button next to each item when the mouse hovers over it. I am currently able to create the "copy" button within the element using the following method: mouseOver(event) { if (event.tar ...

Unlocking rotation on a single screen in a react native application can be achieved by altering

I attempted to use react-native-orientation within a webview in order to make it the only view that would rotate. import React, {useEffect} from 'react'; import { WebView } from 'react-native-webview'; import Orientation from "react-na ...

Confirm button title by verifying part of the label that contains a space

I'm facing an issue with clicking a button using the following code: await page.getByRole('button', { name: '3 Employees' }).click(); The problem is that the button's name fluctuates based on the number of employees, causing ...

Tips for establishing optimal parameters for an object's dynamic property

I am working with an array of objects: export const inputsArray: InputAttributes[] = [ { label: 'Name', type: 'text', name: 'name', required: true }, { label: 'User name ...

The functionality of the "mui-one-time-password-input" is not compatible when used in conjunction with the "formik" library

I'm currently working on a Next.js project, and I need to integrate the mui-one-time-password-input library for OTP input. Additionally, I am using the formik library for form validation. However, I encountered an issue when attempting to set the val ...

The returned type of intersected functions in Typescript does not match the inferred type

While attempting to extract the return type of an intersected request, I encountered a discrepancy between the return type and the inferred type. Check out the shortened URL for more details: https://tsplay.dev/mAxZZN export {} type Foo = (() => Promis ...

Utilizing Angular to parse a JSON string generated with json.dumps

I am having trouble finding a solution that works for me. Currently, I am using python 3.6 (Django Rest Framework) on the server side and Angular 5 on the client side. This is the code on the server: class TypesView(APIView): def get(self,request): ...

MaterialUI/Next.js digital clock selector

I am attempting to display a digital time picker or duration picker (minutes and seconds only) in my project theme, which utilizes material UI and Next.js. I have implemented the materialUI config for this but it always displays an analog clock instead of ...