1

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 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

why didn't I think of this? ty much
0

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!")} />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.