How to check dom for react onKeyDown

Viewed 72

Im creating examples of things that would cause trouble for keyboard only users. I have an element that I created like this:

<div id="role_tab_div_with_react_onclick_has_keydown" role="tab" onClick={() => activateDialog()} tabIndex="0" onKeyDown={() => activateDialog()}>
    <div class="btn-label">Click me (role=tab - has onkeyDown)</div>
</div>

But, when rendered to the DOM, the onKeyDown is not present even thought it is now keyboard activatable.

<div id="role_tab_div_with_react_onclick_has_keydown" role="tab" tabindex="0">
   <div class="btn-label">Click me (role=tab - has onkeyDown)</div>
</div>

So, my check to see if the element already has a onkeydown event:

if (el.hasAttribute('onKeyPress' || 'onKeyDown'))

is not finding it.

Is there a way to determine if it does have a react version of onKeyDown present?

1 Answers

React handles event listeners a little differently than you'd expect. As you pointed out, it does not attach a listener directly to the DOM element it creates/manages. Instead, it attaches a listener higher up the DOM hierarchy and uses the information about the source element to determine which React component manages that element and by extension where to find registered callbacks. You may find this article helpful if you're looking for more of the nitty-gritty: https://dev.to/romaintrotard/under-the-hood-of-event-listeners-in-react-4g01.

Because of the indirect way in which React listens for events you will not have as clear a way to list callbacks. However, there are a few options depending on your use case:

  1. If you know what function is supposed to be called as a callback then you can either add a breakpoint in the browser's debugger or add some sort of side effect to your callback that you can watch for (e.g. console.log()).
  2. If you know the intended side effects of the callback but don't have the ability to find or change the callback function itself, you can look for those instead of the handler itself.
  3. If the code is effectively a black box to you (which it sounds like is the case based on your comment) then there is the ability to look at the React objects attached to that DOM node. This is not part of React's published API and therefore is subject to more frequent or dramatic change than JSX, core components' props, etc.. You may find that some websites have the React internals for a node under __reactInternalInstance$<some suffix> and others have __reactProps$<some suffix>. I would only recommend using it as a last resort and with extreme caution, but it is an option.
Related