Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Last active July 5, 2023 19:47
Show Gist options
  • Save ernestlv/10b52355393c9f58fe36bb5aee8f988b to your computer and use it in GitHub Desktop.
Save ernestlv/10b52355393c9f58fe36bb5aee8f988b to your computer and use it in GitHub Desktop.
#React - Access event object and DOM element
const Square = () => { // Root Functional Component
let listRef = React.useRef(null); // React Hook
const click = (event) => { // event object - 'this' points to window
var domElement = event.target;
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'}} onClick={click}>
{ key }
</div>
);
})
}
</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