REACT: Add Event Listener

Hi, my error is ‘handleKeyPress is not defined’. If I understand correctly the callback is failing - though not sure why. Any help is greatly appreciated. Also, I have tried to write out the code like so for both add and remove, below is an example:

document.addEventListener(‘keydown’, function() {

the error is saying that no event listener is attached

1 Like

Hi @JP-Dub

When inside a class method and referring to other methods/properties in the class, you need to use the this keyword.

// Your's
document.addEventListener('keydown', handleKeyPress);

// What it should be
document.addEventListener('keydown', this.handleKeyPress);


Thank you! I had tried using ‘this’ before the document and in place of document, believing ‘this’ was involved. It never occurred to me to use it in the callback. Again, thank you.