Created
January 30, 2023 19:25
-
-
Save codenickycode/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
This file contains hidden or 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
// 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