1

I would like to dispatch onKeyDown events from a body element too a div inside of the body.

I am using React and have tried adding an onKeyDown event listener to my body tag in the componentDidMount function of my React component.

componentDidMount() {
    document.getElementById("main-content").onkeydown = event => {
        document.getElementById("Keyboard").dispatchEvent(event);
    }
}

I expected the keydown event to be dispatched to the Keyboard component, but instead I receive the error listed below.

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.

Any help would be appreciated!

1 Answers1

0

Can you not hardcode it onto your div element?
Use this question as reference if you can.

If you can't harcode it maybe try this:

    document.querySelector('#yourDiv').addEventListener('keydown', function (event) {
      console.log(event.key) //Change this to whatever you want it to do
    })

Then in your HTML give your div a tabindex="0" property.

The tabindex property:

tabindex="0" allows a non-form/link/object element to be placed in the default navigation order, allowing any element to be focusable and trigger interaction.

More info here

Mick Vader
  • 100
  • 9