Reputation: 3493
My App component passes down an event handler as a prop to a Button Component
// App.js
public handlePlay = () => {
this.setState({ ****** })
}
// render
<Button play={this.handlePlay} />
What is the correct type for the event handler passed via prop i.e. play
?
// Button.js
interface ButtontProps {
play: any //what is the correct type here?
}
export const Button: React.SFC<ButtontProps> = ({ play }) => (
<button onClick={play}>Play</button>
)
I don't want to use any
as that would divert me from applying the correct types for such an instance.
Upvotes: 11
Views: 27952
Reputation: 577
This should work also
import { MouseEventHandler } from "react";
export interface ButtonProps{
play: MouseEventHandler<HTMLButtonElement>
}
export const Button = ({ play }: ButtonProps ) => (
<button onClick={play}>Play</button>
)
Upvotes: 0
Reputation: 15096
The easiest solution would be to use the MouseEventHandler
type with HTMLButtonElement
as the type parameter:
interface ButtonProps {
play: React.MouseEventHandler<HTMLButtonElement>
}
Upvotes: 13
Reputation: 10885
It should most likely be either of the following
(event: React.MouseEvent<HTMLElement>) => void
(event: React.MouseEvent<HTMLInputElement>) => void
You can confirm this by looking at the React typings over here.
Upvotes: 20