I have a function for a keyDown event:
<Table.Row
key={item.id + "-" + index}
className="align-top"
onKeyDown={actionOnEnter(() => {
saveRow(index);
})}
>
I can see in console that event.target
property has a nodeName
property.
I would like to check in the event function the value of the nodeName
property.
export const actionOnEnter = (fn: () => void) => (e: React.KeyboardEvent) => {
console.log(e.target.nodeName);
if (e.key === "Enter") {
e.preventDefault();
fn();
}
};
But, I get typescript error if I try to get a value of nodeName
property:
TS2339: Property nodeName does not exist on type EventTarget
Which property and type should I use to get a node element which triggered the event?
2
Answers
In the context of a
React.KeyboardEvent<Element>
, thetarget
property is typed as anEventTarget
. However,EventTarget
does not have anodeName
property; this property is specific toNode
.The
EventTarget
interface in React only includes methods for adding, removing, or dispatching events.If we know that the event is attached to an element, we can cast the
target
property to aNode
. Alternatively, we can cast it as anElement
orHTMLElement
, depending on the desired specificity.For safer type checking, we can use a guard clause to ensure the
target
is an instance ofNode
before accessingnodeName
:The guard clause narrows the type of
target
within theif
block, allowing it to be treated as aNode
. This ensures type safety and eliminates the need for temporary variables or unsafe casting in that scope.