Home > Enterprise >  How to properly type a button click in React?
How to properly type a button click in React?

Time:08-09

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>

CodePudding user response:

You can use React.MouseEvent

    const handleSortReports= (event : React.MouseEvent<HTMLButtonElement> ) => {
    const button: HTMLButtonElement = event.currentTarget;
    console.log(button.name);
  }
  • Related