'React ref: what is equal to document.querySelectorAll
I have just started with React refs, and I would like to select all icons of ref=this.contentRef. With js I would do it like this: document.querySelectorAll('.content i'). How to do this with the ref?
someMethode() {
const content = this.contentRef.current.childNodes;
const content2 = document.querySelectorAll('.content i');
}
render() {
return (
<div ref={this.contentRef} className="content">
<div>
<i className="fa fa-square" />
</div>
<div>
<i className="fa fa-square" />
</div>
<div>
<i className="fa fa-square" />
</div>
</div>
)
}
Solution 1:[1]
The right way is:
<MyComponent ref={(c) => this.myComponent = c} /> // then check when this.myComponent is NOT undefined
The problem resides on WHAT you want to do with the refs. It is super useful when calling child methods or making calculations (render size etc etc) for all the remaining cases there are alternative patterns that will do the job without refs
Solution 2:[2]
You can actually use QuerySelectorall with ReactDOM.findDOMNode(this) try something like this
const node = ReactDOM.findDOMNode(this);
// Get child nodes
if (node instanceof HTMLElement) {
const child = node.querySelector('.someClass');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mosè Raguzzini |
| Solution 2 | Aqeel aqeelzeid1997 |
