Want to use multiple refs for an array of elements with hooks? A ref is initially just { current: null } object. useRef keeps the reference to this object between component renders. current value is primarily intended for component refs but can hold anything.
1 2 3 4 5 6 7 8 9 |
const elRef = useRef([...Array(3)].map(() => createRef())); ... return ( <div> {[1, 2, 3].map((el, i) => ( <div ref={elRef.current[i]} style={{ width: `${el * 100}px` }}>...</div> ))} </div> ); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.