So I have a React component with a button which has a click handler which uses the data-* attribute. If this was straight React then I know how to get the value from the data-* attribute. However I am learning how to use TypeScript so I have no idea how to get access to this attribute. So what is the best way to get access to the data-* attribute using TypeScript?
This is my JSX code for the button:
<button type="button" className="NavLink" data-appMode={ AppMode.MAIN } onClick={ this.handleAppModeClick.bind(this) }>Main</button>
This is my handler for the click event:
handleAppModeClick(e: React.MouseEvent<HTMLElement>) {
// What code should go here to access the data-appMode attribute?
}
You most likely will have to use as
syntax , depending which property you want to access on e.target.
handleAppModeClick(e: React.MouseEvent) {
const appMode = (e.target as HTMLButtonElement).getAttribute('data-appMode');
}
Use e.currentTarget and then use HTML standard method getAttribute
. No coercion necessary.
const appMode = e.currentTarget.getAttribute('data-appmode');
(note lowercase in the attribute name to avoid warnings from react)
currentTarget
is already correctly typed.If you read the definitions of React's event types you can see that MouseEvent
extends SyntheticEvent
, which extends BaseSyntheticEvent
, which includes the property target
and currentTarget
, among others. The HTMLElement
type you provide gets applied to currentTarget
, so you have access to all the right stuff. If you use target
you'll get a compile error about getAttribute
not being valid for type EventTarget
.
The currentTarget
is the element where you're putting your handler, onClick
. The target
is where the event originally came from (more here). This is not necessarily the same because events bubble up. See the PR referenced in the type definitions file for a complete discussion on why they're typed differently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With