Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get element by component name in ReactJS

Tags:

reactjs

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

like image 890
L. Catalina Meneses Avatar asked Jun 28 '17 12:06

L. Catalina Meneses


People also ask

How do you grab an element by ID in React?

To get an element by ID in React: Set the ref prop on the element. Use the current property to access the element in the useEffect hook.

Can we use getElementById in React?

getElementById() method in React is using refs. To select an element, set the ref prop on it to the return value of calling the useRef() hook and access the dom element using the current property on the ref , e.g. ref. current .


1 Answers

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.

like image 97
Chris Avatar answered Oct 25 '22 17:10

Chris