Sometimes, we want to forward multiple refs with React.
In this article, we’ll look at how to forward multiple refs with React.
How to forward multiple refs with React?
To forward multiple refs with React, we can pass in the refs in an object.
For instance, we write:
import React, { useRef } from "react";
const Child = React.forwardRef((props, ref) => {
const { ref1, ref2 } = ref.current;
console.log(ref1, ref2);
return (
<>
<p ref={ref1}>foo</p>
<p ref={ref2}>bar</p>
</>
);
});
export default function App() {
const ref1 = useRef();
const ref2 = useRef();
const ref = useRef({ ref1, ref2 });
return <Child ref={ref} />;
}
We have the Child
component that accepts refs since we created it by calling forwardRef
with the component function.
In the function, we destructure the refs we pass in by using:
const { ref1, ref2 } = ref.current;
Then we assign ref1
and ref2
to the p elements.
In App
, we create the refs with the useRef
hook.
We create ref
by calling useRef
with an object created from the existing refs.
And finally, we set the ref
prop of the Child
to ref
.
Therefore, from the console log, we can see ref1
and ref2
‘s current
property are assigned to the paragraph elements in Child
.
Conclusion
To forward multiple refs with React, we can pass in the refs in an object.