loading...

React *Cannot read property 'addEventListener' of undefined*

github logo ・1 min read

Another problem with react. I trying to convert vanilla js to react. I have error and i do not have enough knowledge to change it.

Cannot read property 'addEventListener' of undefined

input.addEventListener("keyup", function() {

https://codesandbox.io/s/cocky-shirley-75p85

twitter logo DISCUSS (2)
markdown guide
 

I'm not sure if converting vanilla JS + HTML to React makes sense in some cases.

Nonetheless, whenever cannot read property ... of undefined pops up, you're trying to read a property or execute a function of an object that is undefined. This means that the selector that should fill input results in an empty array, leading to undefined when you're trying to get the element at index 0.

 

When you import a module the code inside it runs immediately. In this case your Count.js file is being run before React has a chance to mount your app and put the textarea into the document. So when you call querySelectorAll, the textarea is not found and input is therefore undefined.

You might consider instead converting that peace to react as well or using a useEffect hook to make sure the code is run only when it's ready to.

Classic DEV Post from Jun 22 '19

Do you have your own Gatsby site? Let's brainstorm a dev.to cross-poster

I'd love it if my blog posts were automatically sent to dev.to - wouldn't you?

ivkeMilioner profile image

Sore eyes?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️