Created
July 5, 2023 19:46
-
-
Save ernestlv/2139976c6193b5a5f3109d66fb0a9e6a to your computer and use it in GitHub Desktop.
#React - Access a DOM element in a dynamic list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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