8

I'm trying to get the listing of a component in the DOM. Something like document.getElementsByTagName("ComponentName") but with a component name.

1
  • 2
    This might be a xy-problem. One of the advantages of React is that you don't have to deal with the DOM directly. Whatever problem you want to solve by doing this might have a simple and ideomatic solution in React itself. Commented Jun 28, 2017 at 12:43

1 Answer 1

5

React Components aren't part of the DOM Model. As such, you cannot get a list of Components from the document object.

What you can do instead is to give the React Components you're interested in finding, a certain css class name, which you then can find in the DOM.


For example:

class MyComponent extends React.Component {
  render(){
    return (
      <div className="myComponent">{this.props.children}</div>
    );
  }
}

class MyApp extends React.Component {
  render(){
    return (
      <div>
        <MyComponent>foo</MyComponent>
        <MyComponent>bar</MyComponent>
      </div>
    );
  }
}

ReactDOM.render(<MyApp />, document.getElementById("myApp"));

/* get components from their class name: */
var list = document.getElementsByClassName("myComponent");
for (var item of list) {
  console.log(item)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="myApp"></div>

You can of course also use id and use document.getElementById() (if the id is unique) or name and use document.getElementsByName(), and other methods. I think class makes most sense.

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

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.