2

I want to pass a function that returns another function to material UI's onTouchTap event:

<IconButton onTouchTap={onObjectClick(object)} style={iconButtonStyle} > <img alt={customer.name} className="object-img" src={object.avatarSrc} /> </IconButton> 

But I keep running into the following error:

Type '{ onTouchTap: Function; style: CSSProperties; tooltip: string; children: Element; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<IconButton> & Readonly<{ children?: ReactNode; }> ...'. 

If I just pass a function, the click event gets fired and everything works:

<IconButton onTouchTap={onObjectClick} style={iconButtonStyle} > <img alt={customer.name} className="object-img" src={object.avatarSrc} /> </IconButton> 

However, the function runs with an event passed, which does not help me. I need to instead pass an object with data in it. Does anyone know how to set a function that returns a function, or a handler to onTouchTap or an onClick event in react using typescript?

1 Answer 1

2

To pass arguments to onTouchTap you need to pass an arrow function and call the function with the desired arguments, like so:

<IconButton onTouchTap={() => onObjectClick(object)} style={iconButtonStyle} > <img alt={customer.name} className="object-img" src={object.avatarSrc} /> </IconButton> 

The reason for this is because onTouchTap and other properties like it take a function object, not a function call. By doing this you're passing an anonymous function (the arrow function) that calls your function with the desired arguments.

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

3 Comments

Be aware that if you define the function inside render(), it'll get recreated every time the component re-renders. A lot of the time this isn't a problem, but if a component is re-rendering often it can cause performance issues. If you run into this issue, define the function as a class property instead (e.g. this.onTouchTap = () => onObjectClick(object), then onTouchTap={this.onTouchTap})
@JoeClay I wasn't aware of that, thanks for the input.
No problem :) It gets mentioned at the bottom of the docs page on handling events, but it's so brief that I think most people miss it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.