0

I have a button, on click on which I need to get the name of the button. How to correctly type event event by typescript? No matter how I tried it, it throws an error.

  const handleSortReports= (event : ??? ) => {
    const {name} = event.target
    console.log(name)
  }

<button id="Period" name="Period" type="button" onClick={handleSortReports}>Test</button>

1 Answer 1

2

You can use React.MouseEvent

    const handleSortReports= (event : React.MouseEvent<HTMLButtonElement> ) => {
    const button: HTMLButtonElement = event.currentTarget;
    console.log(button.name);
  }
Sign up to request clarification or add additional context in comments.

2 Comments

If I use your answer I have this error - TS2339: Property 'name' does not exist on type 'EventTarget'.
@Timofeus91 I've updated my answer. Please check again.

Your Answer

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