randombits
randombits

Reputation: 48450

TypeScript correct way to type onChange handler

I have a simple controlled input that looks like the following:

<textarea
  name="description"
  onChange={updateEdit}
  value={edit}
  placeholder={edit}
/>

my updateEdit handler

const updateEdit = (evt: React.ChangeEventHandler<HTMLTextAreaElement>) => {
    const updatedEdit: Edit = { id: proposalId, value: evt.target.value };
    dispatch(setEditForProposal(updatedEdit));
};

Property 'target' does not exist on type 'ChangeEventHandler<HTMLTextAreaElement>'

What's the correct way to type this?

Upvotes: 1

Views: 501

Answers (2)

Yilmaz
Yilmaz

Reputation: 49190

I think you are typing the React.ChangeEventHandler in wrong place. should be

 const updateEdit: React.ChangeEventHandler<HTMLTextAreaElement>=(event){}

it is for handler itself but you are using for the argument of the function

Upvotes: 1

Angshu31
Angshu31

Reputation: 1270

Use

const updateEdit = (evt: React.ChangeEvent<HTMLTextAreaElement>) => {

The reason is you typed it as a ChangeEventHandler, which means a function that takes in a ChangeEvent. Or you could type the function as the handler

const updateEdit: React.ChangeEventHandler<HTMLTextAreaElement> = (evt) => {

Upvotes: 1

Related Questions