I'm trying to get the listing of a component in the DOM. Something like
document.getElementsByTagName("ComponentName")
but with a component name.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With