11

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.

3 Answers 3

20

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.

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

4 Comments

Thank you, Christian. Are you suggesting that inside the handlePlay(event: ...)?
For play in ButtonProps definitely. handlePlay can omit this if it doesn't use the event in the first place due to the nature of JavaScript allowing parameter omission.
I'm failing to translate your suggestion into my current code example in the question above. I added onClick={(e: React.MouseEvent<HTMLElement>) => playAgain} but it errors type is not assignable to intrinsic attributes
@Jonca33 Do it as shown in the answer of Oblosys. It suffices to replace your any that you annotated in the first place with either of our solutions.
13

The easiest solution would be to use the MouseEventHandler type with HTMLButtonElement as the type parameter:

interface ButtonProps {
  play: React.MouseEventHandler<HTMLButtonElement>
}

Comments

0

This should work also

import { MouseEventHandler } from "react";

export interface ButtonProps{
    play: MouseEventHandler<HTMLButtonElement>
}

export const Button = ({ play }: ButtonProps ) => (
  <button onClick={play}>Play</button>
)

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.