Compose Refs 🔗
Greetings, Ref Master! 🧙♂️
Ever found yourself in a tricky situation where you need to attach multiple refs to a single React component? 🤔 The compose-refs
module is here to save the day! It elegantly merges multiple refs into a single ref callback that you can pass to your component.
It's like a Voltron for your refs, combining their powers! 🤖
Why, though?
Sometimes you have a forwardedRef
from a parent, and you also need an internal ref to the same DOM element for measurements or imperative calls. This module makes that clean and easy.
Basic Usage
import { useComposedRefs } from '@ryvora/react-compose-refs';
import React, { useRef } from 'react';
const MyComponent = React.forwardRef((props, forwardedRef) => {
const internalRef = useRef<HTMLDivElement>(null);
const composedRefs = useComposedRefs(forwardedRef, internalRef);
// Now, if forwardedRef exists, it will be updated.
// And internalRef will also point to the div!
return <div ref={composedRefs}>Hello!</div>;
});
Ref-tastic! 💫 Keep those refs in check!