Additional arguments for React event handlers (using functional components)

Viewed 97

I want to pass an additional argument to onChange (event handler) of an <input> tag, apart from the event object. How do I do that?

Suppose, I have such a function

const f = (event, i) => {//stuff}

Can I do this? (I know it doesn't work)

<input onChange=f(1) />

Assuming, the event object gets passed in as the first argument automatically?

Note - I am using functional components

2 Answers

To pass an argument to onChange handler of tag, you can do the following:

<input type="text" onChange={ (event)=>f(event,i) } />

Although event object is automatically available, you will have to pass it to the function so as to make use of it.

I wanted an idiomatic TypeScript solution, so, for all the awesome TypeScripters out there, in the wild:
React v18
Declare and define a custom event handler as shown below:

import type { ChangeEvent, SyntheticEvent } from "react";

type MyCustomEventHandler<E extends SyntheticEvent<any>> = {
  bivarianceHack(event: E, ...args: any): unknown;
}["bivarianceHack"];
type MyCustomChangeEventHandler<T = Element> = MyCustomEventHandler<ChangeEvent<T>>;

// Declare and define your custom function
// with as many as arguments as your desire.
const f: MyCustomChangeEventHandler = (event, i: string) => { /*stuff*/ };

Doing so will keep the TypeScript linter happy!

<input type="text" onChange={(event) => f(event, "God is a programmer!")} />
Related