So I have an array of data in and I am generating a list of components with that data. I\'d like to have a ref on each generated element to calculate the height. I know how
I created a tiny npm
package that exposes a React Hook
to handle setting and getting refs dynamically as I often run into the same problem.
npm i use-dynamic-refs
Here's a simple example.
import React, { useEffect } from 'react';
import useDynamicRefs from 'use-dynamic-refs';
const Example = () => {
const foo = ['random_id_1', 'random_id_2'];
const [getRef, setRef] = useDynamicRefs();
useEffect(() => {
// Get ref for specific ID
const id = getRef('random_id_1');
console.log(id)
}, [])
return (
<>
{/* Simple set ref. */}
{/* Set refs dynamically in Array.map() */}
{ foo.map( eachId => (
Hello {eachId}))}
>
)
}
export default Example;