I have encountered a scenario where I need to pass the ref of an element in child to the parent. I could not do this using the "forwardRef" approach as I render a list of children in the parent component.
I have passed the ref from the child as a method parameter to one of the parent method which is accessible via props. This works and I was able to access the ref in the parent to achieve what I wanted.
I want to know if this approach would result in any future problem or if it is an anti-pattern. Please let me know if the same can be achieved through any other means.
Below is a sample code demonstrating my implementation.
export const Child: React.FC<any> = (props: any) => {
const childRef = useRef<any>(null);
const clickHandler = () => {
props.onListItemClick(childRef);
};
return (
<li onClick={clickHandler} ref={childRef}>
{props.key} - {props.item.name}
</li>
);
};
export const Parent: React.FC<any> = (props: any) => {
const listItemClickHandler = (clickedChildRef: any) => {
// use the child ref to set the scroll
if (clickedChildRef && clickedChildRef.current) {
clickedChildRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
};
return (
<ol>
{props.data.map((item: any, index: number) =>
<Child item={item} key={index} onListItemClick={listItemClickHandler} />
)}
</ol>
)
};
2
Answers
Your approach might work, not sure. But there is official example for working with list of refs (here I have adapted it for custom components):
For posterity,
useRef
here is superfluous, the two snippets are equivalent in functionality:When you could just do this: