Reputation: 2568
I have a div
container that wraps a third part component that renders to following
<div id="selector">
<div id="selector-1"/>
<div id="selector-2"/>
<div id="selector-3"/>
</div>
I create a ref for the div container and i can access it fine. But how do i use that ref to access a specific child element say selector-2
? Is it possible to add a ref element to the rendered child(third part component) directly? Currently i use document.getElementById('selector-2') to access that element.
<div ref={this.myref}>
<ThirdpartyComponent/>
</div>
Upvotes: 2
Views: 9810
Reputation: 161
Just VanillaJS...
Not sure why anything other than the direct access via id using getElementById is desired, but you could process a list of the outer div's children, looking for an element with the given value of its id (or any other) property or by desired index position in the child collection.
function getKids(eref, cId, idx) {
// kids is a list of all *direct* children of eref
var kids = eref.children;
console.log(kids);
// kid is the particular node by id attribute with value cId
var kid = null;
// find kid by id
for (var i = 0; i < kids.length; i++) {
if (cId == kids[i].id) {
kid = kids[i];
break;
}
}
// log kid found by search on id
console.log(kid);
// log kid found by index (-1 for 0 index origin)
console.log(kids[idx - 1]);
};
I added styles to provide click target in the page - expanded div declarations to include closing tags to ensure capture as elements of the list for the children property of the outer, parent div element. getKids finds the desired item either by id or index in the list of children.
<div id="selector" onclick="getKids(this, 'selector-2', 2);"
style="padding:5px;width:10px;background-color:red;"
>
<div id="selector-1"></div>
<div id="selector-2"></div>
<div id="selector-3"></div>
</div>
Upvotes: 0
Reputation: 36594
You can do that using ReactDOM.findDOMNode()
and Element.querySeletorAll()
. Below is a demo
class Three extends React.Component{
render() {
return(
<React.Fragment>
<div id="selector-1">One</div>
<div id="selector-2">Two</div>
<div id="selector-3">Three</div>
</React.Fragment>
);
}
}
class App extends React.Component{
myRef="comp"
render() {
return(
<div ref={this.myRef}>
<Three/>
</div>
);
}
componentDidMount = () => {
let x = ReactDOM.findDOMNode(this.refs[this.myRef]);
console.log([...x.querySelectorAll('div #selector-2')]);
}
}
const app = document.getElementById('root');
ReactDOM.render(<App>Something Else</App>, app);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 1