2

Is there a way to detect if an HTML Element is the root of any React component in a production app?

I'm not referring to detecting wether an element is the root of the entire React application, rather detecting if an element is the root of any component.

To illustrate:

Let's say we have the following React components:

const FooBar = () => {
  return (
    <div className="foobar">
      <span> foo </span>
      <button> bar </button>
    </div>
  );
}

const Container = () => {
  return (
    <div>
      <a className="john"> john </a>
      <a> doe </a>
      <FooBar />
    </div>
  );
}

That transpiles to the following HTML:

<div>
  <a class="john"> john </a>
  <a> doe </a>
  <div class="foobar">
    <span> foo </span>
    <button> bar </button>
  </div>
</div>

In a production deployment, is there a way to do this from a chrome extension (external script)? and how?

const foobarDiv = document.querySelector('div.foobar');
const span = document.querySelector('span');
const a = document.querySelector('a.john');
isReactComponentRoot(foobarDiv); // true
isReactComponentRoot(span); // false
isReactComponentRoot(a); // false

2 Answers 2

2

I don't know if this will continue to be reliable in the future, but something that's worked for a while is to check if it has a _reactRootContainer property.

const root = document.querySelector('.react');
const App = () => {
    return <div className="child"></div>;
};

ReactDOM.render(<App />, root);

console.log(root.hasOwnProperty('_reactRootContainer'));
console.log(root.querySelector('.child').hasOwnProperty('_reactRootContainer'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this, but I actually wasn't referring to detecting the root of the entire React app, rather detecting if an element is the root of any React component. I just rephrased the question with more clarification.
0

I have this exact need, there is an internal function inside ReactDom that determines if a domNode is a react root or not.

I think the cheeky way to do this would be to see if the domNode has a prop that starts with _react.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.