How to get an element by component name in ReactJS

I am trying to get a list of components in the DOM. Something like document.getElementsByTagName("ComponentName")that, but with the name of the component.

+4
source share
1 answer

React Components are not part of the DOM model. Therefore, you cannot get a list of components from an object document.

Instead, you can give the React Components that you are interested in finding a specific css class name that you can find in the DOM.


For instance:

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>
Run codeHide result

You can also use idand use document.getElementById()(if idunique) or nameuse document.getElementsByName()other methods. I think that classmakes sense.

+2
source

Source: https://habr.com/ru/post/1680305/


All Articles