Skip to content

Instantly share code, notes, and snippets.

@drumnickydrum
Created January 30, 2023 19:25
Show Gist options
  • Save drumnickydrum/12898b470f3690472b9466726814dcd8 to your computer and use it in GitHub Desktop.
Save drumnickydrum/12898b470f3690472b9466726814dcd8 to your computer and use it in GitHub Desktop.
[React: Ref callback] Use a ref callback to set a list of nodes #react #ref #useRef #dom
// https://beta.reactjs.org/learn/manipulating-the-dom-with-refs#how-to-manage-a-list-of-refs-using-a-ref-callback
// in the function body
const itemsRef = useRef(null);
function getMap() {
if (!itemsRef.current) {
// Initialize the Map on first usage.
itemsRef.current = new Map();
}
return itemsRef.current;
}
// on the element
{catList.map(cat => (
<li
key={cat.id}
ref={(node) => {
const map = getMap();
if (node) {
map.set(cat.id, node);
} else {
map.delete(cat.id);
}
}}
/>
))}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment