you can use cloneElement which helps us to clone and return a new React element using an element as the starting point. by this, we can add ref to element props, first, we made an array of childrens, then add our ref to the first one, e.g:
function Wrapper({ children }) {
const testRef = React.useRef(undefined);
const addReftoFirstChild = (chilrens, ref) => {
let elements = React.Children.toArray(chilrens);
return [React.cloneElement(elements[0], { ref })].concat(elements.slice(1));
};
return (
<>
{addReftoFirstChild(children, testRef)}
<button onClick={() => console.log(testRef.current)}>Test Ref!</button>
</>
);
}
function App() {
return (
<Wrapper>
<img
src='https://www.publicdomainpictures.net/pictures/80000/velka/odd-eyed-kitten.jpg'
width={200}
height={125}
/>
<img
src='https://c.files.bbci.co.uk/12A9B/production/_111434467_gettyimages-1143489763.jpg'
width={200}
height={125}
/>
</Wrapper>
);
}