Typescript onclick function in React JS

Viewed 28

I have this code in my react js application:

 <button onClick={tes} type="button">click</button>

and this is my tes function:

const tes = (id: string) => {
    console.log(id)
}

If i hover over onClick function TS engine return:

TS2322: Type '(id: string) => void' is not assignable to type 'MouseEventHandler<HTMLButtonElement>'.   Types of parameters 'id' and 'event' are incompatible.     Type 'MouseEvent<HTMLButtonElement, MouseEvent>' is not assignable to type 'string'.

Question: How to fix this and to add correct types?

1 Answers

You can't control the type of event that is passed as a parameter to the onClick handler function. But you can use a dummy middleware function and call your custom handler with a custom parameter by doing something like this:

<button onClick={() => tes("myid")} type="button">click</button>

const tes = (id: string) => {
    console.log(id)
}
Related