Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - get React component from a child DOM element?

I'd like to be able to figure out what React component is associated with a certain DOM element.

For example, say I have a div, and I'm rendering my entire application using React. The div has to be rendered by a React component - but which one?

I know that React supplies the method "getDOMNode" to get the DOM node associated with a React component, but I'd like to do the opposite.

Is this possible?

like image 204
Brad Parks Avatar asked Jun 28 '14 01:06

Brad Parks


People also ask

How do you get the DOM React component?

Access a DOM Element Using ReactDOM.findDOMNode() . findDOMNode() is used to find a specific node from the DOM tree and access its various properties, such as its inner HTML, child elements, type of element, etc. In short, it can return all the supported DOM measurements related to the kind of element.

How do you access children of elements in React?

In React we can access the child's state using Refs. we will assign a Refs for the child component in the parent component. then using Refs we can access the child's state. Creating Refs Refs are created using React.

How do you access a specific DOM element in React?

In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method. Creating Refs: Refs are created using React. createRef() and attached to React elements via the ref attribute.

How do you get parent data from a child in React?

React. js allows us to use props (short form of property) to pass data from parent component to child component. We have to set props value inside the child component, while we embed it to the parent component.


1 Answers

No.

A central concept in React is that you don't actually have a control in the DOM. Instead, your control is that factory function. What's in the DOM is the current render of the control.

If you actually need this, you can keep an object as a global variable, whose keys are the string representations of the names of factory functions, and whose values are the factory functions, then on your renderable div, keep an attribute containing the name of the factory function.

But chances are this is a question of the XY problem (needing X, seeing a way with Y, then asking how to do Y.) Probably if you'd explain your goal there's a better way that better fits React's top-down conceptual model.

Generally speaking, asking to get access to the control from its render is like asking to get access to an SVG from its cached PNG render. It's possible, but it's usually a red flag that something else is conceptually wrong.

like image 74
John Haugeland Avatar answered Sep 28 '22 08:09

John Haugeland