HooksuseRefList

useRefList

A React hook that creates refs for a list of elements.

Installation

npm install @madeinhaus/hooks

Import

import { useRefList } from '@madeinhaus/hooks';

Returns

  • refFn (function): A function that takes an index and returns a ref callback for an element at that index.
  • refs (object): A mutable ref object that holds an array of elements.

Usage

import { useEffect } from 'react';
import { useRefList } from '@madeinhaus/hooks';
 
function MyComponent({ someCollection }) {
  const [refFn, refs] = useRefList<HTMLDivElement>();
 
  useEffect(() => {
    // refs.current is an array of elements
    // refs.current[0] is the first element,
    // refs.current[1] is the second element, etc.
    refs.current.forEach(element => {
      // do something with each element
    });
  }, []);
 
  return (
    <div>
      {someCollection.map((item, index) => (
        <div ref={refFn(index)} key={index}>
          {item}
        </div>
      ))}
    </div>
  );
}