Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react: addEventListener is not a function error

Tags:

reactjs

i have this div inside my render method in a component

<div ref={node => this.domNode = node} style={this.getStyle()}>{ this.props.children }</div>

when i do this in componentDidMount

this.domNode.addEventListener('mousedown', this.onDrag); 

there is an error

this.domNode.addEventListener is not a function
like image 613
scully Avatar asked Sep 03 '16 19:09

scully


People also ask

What is the use of event listener in JavaScript?

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.

What does false mean in addEventListener?

addEventListener("click", first, true); when clicking child element, first method will be called before second . By default, the useCapture flag is set to false which means you handler will only be called during event bubbling phase.


2 Answers

You have to put a ReactDOM.findDOMNode around it.

componentDidMount = () => {
   ReactDOM.findDOMNode(this.domNode).addEventListener('mousedown', this.onDrag);
}
like image 159
Freddy Ochner Avatar answered Nov 13 '22 20:11

Freddy Ochner


The arguemnt (node) of your ref callback can be null. You need to check that before you bind your listener.

Note that when the referenced component is unmounted and whenever the ref changes, the old ref will be called with null as an argument.

from https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute

like image 38
Scarysize Avatar answered Nov 13 '22 20:11

Scarysize