Incorrect tsx date interpretation when dealing with years such as 0022

I am facing an issue with dates in tsx. The problem lies in the fact that when I set a date like 30/11/0022, it interprets the date as 30/11/1922, which is incorrect.

Here is the input element I have in tsx:

<FormikField name="Birthdate" disabled={FormState.loading}/>

The FormikField is defined as follows:

interface Props {
  name: string;
  autoFocus?: boolean;
  hidden?: boolean;
  disabled?: boolean;
  component?: React.Component;
  label?: string;
  className?: string;
  disableAutocomplete?: boolean; 
}

export const FormikField = ({ ...props }: Props) => {
  // code implementation
};

The Birthday type definition can be found here:

Birthdate:{
        type: 'date',
        defaultvalue: null,
        placeholder: 'Set your birthday',
        validations: yup.date()
                        .required('The field is needed')
                        .min(new Date(new Date().getFullYear() - 120, new Date().getMonth(), new Date().getDate()), 
                            'The birthday cannot be more than 120 years ago')
                        .max(new Date(new Date().getFullYear() - 1, new Date().getMonth(), new Date().getDate()),
                            'The birthday cannot be less than 1 year ago.')
    }

Is there any way to resolve this issue? Please note that I am using getFullYear()

Answer №1

Formik lacks built-in support for handling dates effectively and is gradually becoming less supported. The default onChange function in Formik only looks for the e.target.value property, which, even on a date input with type="date", will return a string.

This creates issues because now you are storing a string representation of a date in the form state, which is much more ambiguous than a true date object. At some point, this string may be converted back into a date, triggering JavaScript's default date parsing mechanism that has complexities when it comes to certain date formats.

It is preferable to store an actual date in your form state, which can be accessed using e.target.valueAsDate in the onChange function instead.

Therefore, we need to override the onChange function and verify if the field is a date type. If it is, custom code is used to set the field value as valueAsDate. Otherwise, the default Formik onChange function is executed.

Unique code block provided...

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

Cross-origin error triggered by using an external API within a ReactJS application

I'm facing a common CORS issue in my application while trying to call an API. The API I am attempting to access can be found here: https://github.com/nickypangers/passport-visa-api Below is the code snippet used for making the API call: const getVi ...

Is it possible to dynamically create an interface using an enum in TypeScript through programmatically means?

Recently, I defined an enum as shown below: enum EventType { JOB, JOB_EXECUTION, JOB_GROUP } Now, I am in need of creating an interface structure like this: interface EventConfigurations { JOB: { Enabled?: boolean; }; JOB_EXECUTION: { ...

Why aren't the child route components in Angular 6 loading properly?

I have encountered a small problem. I developed an app using Angular 6 with children routes implemented like this: { path:'pages', component:DatePagesComponent, children : [ {path:'404', component:Error404C ...

Loading a large quantity of items into state in React Context using Typescript

I am currently working on a React context where I need to bulk load items into the state rather than loading one item at a time using a reducer. The issue lies in the Provider initialization section of the code, specifically in handling the api fetch call ...

Issue with Angular 2 Custom Pipe not Refreshing Unless Object is Saved

I recently created a custom Angular 2 pipe that formats a phone number from a 10-digit string to 'XXX-XXX-XXXX'. The pipe is functioning perfectly, but the issue arises when it fails to update in real-time during keypress; instead, it updates onl ...

This TypeScript error occurs when the type of a CSS file lacks an index signature, resulting in an implicit 'any' type for the element

Currently in the process of transitioning a React app to utilize Typescript. Encountering an error message that reads: ERROR in [at-loader] ./src/components/Services/Services.tsx:34:29 TS7017: Element implicitly has an 'any' type because typ ...

Tips for adjusting the font color of user-provided text within an input box using HTML and CSS

HTML code:- <p><input type="text" placeholder="Enter your username"></p> CSS code:- .main-header input { width: 90%; padding: 1rem; margin: 20px 0px; border: none; border-bottom: 4px solid #5f5fb0; ...

Decorators in Angular 9 do not have the capability to support function expressions

Currently, I am working with Angular 9 and facing an issue while generating dynamic routes values during runtime. I have implemented a ComplexUrlRouter to achieve this functionality and integrated it into my Route configuration. However, I encountered the ...

essential elements for mapping an array using typescript

Struggling to iterate through an array of objects, each with a unique id created by uuidv4(), resulting in a string type. TypeScript is giving errors (( Type 'String' is not assignable to type 'Key | null | undefined')) due to the &apos ...

Observable map encounters an error when attempting to retrieve essential data from the backend server

Here is my approach: getDropdownData(id: number | 195731): Observable<ClinicTrialSettingProp> { return this.http .get<ClinicTrialSettingProp>(this.commonPatientURL + id + '/clinic-trials') .pipe(map(response => res ...

In what ways can enhancing the TypeScript type system with additional restrictions help eliminate errors?

Encountered issues while working on my TypeScript project due to errors in the type definitions of a library. The solution was to enable the strictNullChecks flag. It seems counter-intuitive that adding restrictions can eliminate errors, when usually it&a ...

Exploring the concept of abstract method generation in TypeScript within the Visual Studio Code

Anyone familiar with a Visual Studio Code plugin that can automatically generate stub implementations for abstract methods and properties in TypeScript? I've searched through the available plugins but haven't been able to locate one. Any suggest ...

When trying to retrieve a value from a custom render function in React with TypeScript, an error occurs indicating that the value is not assignable to type 'ReactNode'

Recently, I attempted to develop a versatile swiper component using Next.js 13 (App Router) v13.4.12 along with TypeScript. However, I encountered an issue when trying to access data from the component props, which involves a custom function for rendering ...

Using TypeScript with Vue: Safely accessing component properties in a type-safe manner

I am currently exploring Vue's setup API and there is one aspect that I am struggling with: I need to retrieve properties of a child component from a parent component. Everything seems to be functioning correctly, but I am facing difficulties with the ...

Can a single file in NextJS 13 contain both client and server components?

I have a component in one of my page.tsx files in my NextJS 13 app that can be almost fully rendered on the server. The only client interactivity required is a button that calls useRouter.pop() when clicked. It seems like I have to create a new file with ...

What causes the discrepancy in results between these two NodeJS/Typescript imports?

Within my NodeJS project, I have integrated typescript version 3.2 alongside express version 4.16 and @types/express version 4.16. My development is focused on using Typescript with the intention of transpiling it later on. The guidelines for @types/expre ...

Interactive Bootstrap 4 button embedded within a sleek card component, complete with a dynamic click event

I am trying to create a basic card using bootstrap 4 with the following HTML code. My goal is to change the style of the card when it is clicked, but not when the buttons inside the card are clicked. Currently, clicking on the test1 button triggers both ...

Adjust the alignment of divs in Angular

In developing a dashboard, I have successfully displayed key value pairs in a component by retrieving them from an environment.ts file. Now, I am looking to rearrange the positioning of the individual testcard components to align with a specific layout sho ...

Refreshing the list in a Next.js to-do application post-deletion: a step-by-step guide

I am currently developing a basic to-do application using Next.js, TypeScript, and Axios. I have successfully implemented the delete functionality for tasks, but I am facing an issue with refreshing the tasks list after deletion. I would appreciate any s ...

Angular 10 Reactive Form - Controlling character limit in user input field

I'm currently developing an Angular 10 reactive form and I am looking for a way to restrict the maximum number of characters that a user can input into a specific field. Using the maxLength Validator doesn't prevent users from entering more chara ...