Skip to content
Advertisement

React – getting a component from a DOM element for debugging

For the purposes of debugging in the console, is there any mechanism available in React to use a DOM element instance to get the backing React component?

This question has been asked previously in the context of using it in production code. However, my focus is on development builds for the purpose of debugging.

I’m familiar with the Chrome debugging extension for React, however this isn’t available in all browsers. Combining the DOM explorer and console it is easy to use the ‘$0’ shortcut to access information about the highlighted DOM element.

I would like to write code something like this in the debugging console: getComponentFromElement($0).props

Even in a the React development build is there no mechanism to use maybe the element’s ReactId to get at the component?

Advertisement

Answer

I’ve just read through the docs, and afaik none of the externally-exposed APIs will let you directly go in and find a React component by ID. However, you can update your initial React.render() call and keep the return value somewhere, e.g.:

window.searchRoot = React.render(React.createElement......

You can then reference searchRoot, and look through that directly, or traverse it using the React.addons.TestUtils. e.g. this will give you all the components:

var componentsArray = React.addons.TestUtils.findAllInRenderedTree(window.searchRoot, function() { return true; });

There are several built-in methods for filtering this tree, or you can write your own function to only return components based on some check you write.

More about TestUtils here: https://facebook.github.io/react/docs/test-utils.html

Advertisement