react event target parent node

Simon Tsang picture Simon Tsang · Jan 30, 2017 · Viewed 12.9k times · Source

Is it possible to get the event target's parent node on the virtual DOM?

In my basic react component I have a method which is triggered from onClick event, I would like to get the parent virtual DOM node properties.

handleClick(e){ 
    // The following code only gives me the actual DOM parent Node
    ReactDOM.findDOMNode(e.target).parentNode 

}

Answer

prosti picture prosti · Jan 30, 2017

Yes. React works on a virtual DOM model, and will update the real Browser DOM only if needed. The events in React work on a virtual DOM also and they are called synthetic events. If you find that you need the underlying browser level event for some reason, simply use the nativeEvent attribute to get it.

There are some constraints in React Virtual DOM that you may read from here:

Also, this may be helpful and explains the difference between the Virtual Dom and Browser DOM.


Browser DOM is just an abstraction of the on page elements, and React DOM would be an abstraction of that abstraction.

The render method of ReactDOM is crucial how we send React elements to Browser DOM:

var React = require('react');
var ReactDOM = require('react-dom');
var root = React.createElement('div');
ReactDOM.render(root, document.getElementById('example'));
        ^ 
        |---- Where React elements from React Virtual DOM enter the Browser DOM

In React we are dealing with React Elements and React Components.

enter image description here

Since React Element is a virtual representation of a DOM Element, to work with the events and catch the parents, you need to create React Components either of these three ways:

enter image description here

To navigate the parent inside the click Event for instance you may check this:

 var parent = this._reactInternalInstance._currentElement._owner._instance;

REF: is there any way to access the parent component instance in React? and http://jsfiddle.net/BinaryMuse/j8uaq85e/