Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Created July 5, 2023 19:46
Show Gist options
  • Save ernestlv/2139976c6193b5a5f3109d66fb0a9e6a to your computer and use it in GitHub Desktop.
Save ernestlv/2139976c6193b5a5f3109d66fb0a9e6a to your computer and use it in GitHub Desktop.
#React - Access a DOM element in a dynamic list
const Square = () => { // Root Functional Component
let listRef = React.useRef(null); // React Hook
const click = () => { // 'this' points to window
var children = listRef.current.querySelectorAll('div');
var domElement = children[2]; // third DOM element
alert(domElement.textContent);
}
console.log("render square");
// View
return (
<div ref={listRef} style={{ backgroundColor:'blue'}}>
{
[1,2,3].map((key) => {
return (
<div key={key} style={{ margin:'1rem', textAlign:'center', backgroundColor:'red'}}>
{ key }
</div>
);
})
}
<button onClick={click}>Access Third Element</button>
</div>
);
}
const root = ReactDOM.createRoot(document.querySelector("#app"));
root.render(<Square />);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment