When developing low-level UI components, it’s common to have to use a local ref but also support an external one using React.forwardRef
. However, React doesn’t offer a way to set two refs inside the ref
property. This is where react-merge-refs comes in – a small utility that handles compatibility for you.
Installation
You can install react-merge-refs using npm or yarn:
npm install react-merge-refs
Basic Usage
Let’s start with a simple example. Suppose we have a component that needs to use a local ref and also support an external ref:
import React from "react";
import { mergeRefs } from "react-merge-refs";
const Example = React.forwardRef(function Example(props, ref) {
const localRef = React.useRef();
return <div ref={mergeRefs([localRef, ref])} />;
});
In this example, we’re using mergeRefs
to merge the local ref localRef
with the external ref ref
. This allows us to use both refs in our component.
Advanced Usage
What if we need to merge multiple refs? No problem mergeRefs
can handle that too:
import React from "react";
import { mergeRefs } from "react-merge-refs";
const Example = React.forwardRef(function Example(props, ref) {
const localRef1 = React.useRef();
const localRef2 = React.useRef();
return <div ref={mergeRefs([localRef1, localRef2, ref])} />;
});
In this example, we’re merging three refs: localRef1
, localRef2
, and ref
.
Conclusion
react-merge-refs is a simple yet powerful utility that helps you merge refs in React. With its basic and advanced usage examples, you can easily integrate it into your projects and start merging refs like a pro