1
0 Comments

Open Source: React hook to get and set refs dynamically

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!

posted to Icon for group Developers
Developers
on April 13, 2020
Trending on Indie Hackers
I got my first $159 in sales after realizing I was building in silence User Avatar 52 comments Three Days Before Launch, I Let My Own Tool Tear Me Apart User Avatar 36 comments I thought I was building a news visualization tool. Users thought it was a catch-up tool. User Avatar 34 comments I got tired of rewriting the same content for 9 different platforms. So I built Repostify. User Avatar 30 comments I Rejected a $15K Acquisition Offer for My Multi-Agent IDE — Here's the Full Breakdown User Avatar 28 comments A pattern I keep seeing in EdTech: traffic isn't usually the problem. User Avatar 23 comments