How to handle onChange in Typescript
Asked Answered
C

1

14

I am new to Typescript. How do you normally handle onChange in TextField, when using Typescript language?

  • The function handleChangeDate(e: React.ChangeEvent<any>) in the code below works, but I get warnings because I use the type any. Which other way can I write this code?

import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { TextField } from '@material-ui/core';

const [date, setDate] = useState(
    new Date().getDate() + '/' + (new Date().getMonth() + 1) + '/' + new Date().getFullYear(),
);

const handleChangeDate = (e: React.ChangeEvent<any>): void => {
    setDate(e.target.value);
};
Convincing answered 8/4, 2020 at 12:28 Comment(0)
F
27

For MUI TextField (v5.10.11)

event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>
Fruitful answered 8/4, 2020 at 12:36 Comment(2)
I get the following error: TS2345: Argument of type 'string' is not assignable to parameter of type 'SetStateAction '.Monochasium
@Monochasium Works fine in my case; the error is likely not related to event, but with this: How can I define type for setState when React.Dispatch<React.SetStateAction<string>> not accepted?Biquadratic

© 2022 - 2024 — McMap. All rights reserved.