I am trying to get the the key from a element that is mapped from a database ( I am only saying this so nobody suggests to useState)
listedItems.map((e)=> (
<div
ref={ref}
key={e.openRequestDocId}> // Need to get this Key
<button onClick={()=> console.log(ref)}
>get Key from useRef</button>
</div>
I have created a codeSandbox mockup of where I am at. Basically, I have a ref from React.useRef(), and I am trying to get the key prop from the parent div.
https://codesandbox.io/s/mutable-sea-5qony2?file=/src/App.js
All help is appreciated!
you can attach additional data to ref(s) using useImperativeHandle hook like the following:
import React, { useRef, useImperativeHandle } from "react";
export default function App() {
const ref = useRef();
useImperativeHandle(ref, () => ({
key: "A3hNc95uj"
}));
const handleClick = () => {
console.log(ref);
};
return (
<div className="App" key={"A3hNc95uj"} ref={ref}>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={handleClick}>Log Key from parent div</button>
</div>
);
}
Set your key in a data- attribute (for a simple name right now: data-key). And then from the ref, since you get the div element, you can fetch it again by doing ref.current.dataset.key
The only downside of this approach is that the key will be visible in the DOM. If that shouldn't be the case then you can create a closure for the button onClick with the key
<button onClick={(event) => myfunction(event, e.openRequestDocId)}>
get Key from useRef
</button>
This way, your click handler will get the required key onClick