Just published a small npm package to solve one of my major pains with React - setting and getting component refs dynamically. This was especially painful because I needed to pass the created refs to multiple components, and sometimes layers deep within the component tree.
Previously I'd have to do something toward :
const Before = () => {
const foo = ['random_id_1' , 'random_id_2']'
const refsArray = foo.map(() => createRef());
return (
<div>
{data.map( eachId => (
<div ref={refsArray[index].current} key={eachId}/>)}
</div>
);
};
And in order to use a ref later , perhaps return an array of objects in refsArray with an id key like so
const refsArray = foo.map(eachId => ({id: eachId, ref: createRef()}));
With use-dynamic-refs hook, you can simply do :
npm i use-dynamic-refs
and then,
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 id1 = getRef('random_id_1');
console.log(id1)
}, [])
return (
<>
{/* Simple set ref. */}
<span ref={setRef('random_id_3')}></span>
{/* Set refs dynamically in Array.map() */}
{ foo.map((eachId, idx) => (
<div ref={setRef(eachId)}> Hello {eachId} </div>))}
</>
)
}
Github Repo :
https://github.com/fitzmode/use-dynamic-refs
NPM:
https://www.npmjs.com/package/use-dynamic-refs
Feedback and PR's welcome!