This component takes children and assign ref to each child by recreating element. It works with HTML elements but it doesn't work with components and It gives me this error when I put a component as its child:
react-dom.development.js:86 Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of `FadeInChildren`.
at Button (http://localhost:5173/src/components/Button.tsx:18:3)
at FadeInChildren (http://localhost:5173/src/components/FadeInChildren.tsx:20:3)
Would there be any way I can use ref to child components?
import {
useState,
useRef,
useEffect,
Children,
cloneElement,
createElement,
} from "react";
import "./FadeInChildren.css";
const FadeInChildren = ({
children,
toLeft,
}: {
children: any;
toLeft?: boolean;
}) => {
const [isVisible, setVisible] = useState(
Children.toArray(children).map(() => false)
);
const childRefs = useRef<Array<HTMLElement | null>>([]);
useEffect(() => {
childRefs.current.forEach((childRef, i) => {
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setVisible((prevIsVisible: any) =>
prevIsVisible.map((visible: any, index: any) =>
index === i ? true : visible
)
);
observer.unobserve(entry.target);
}
});
},
{ rootMargin: "-20% 0% -20% 0%" }
);
if (childRef) {
observer.observe(childRef);
}
return () => {
observer.disconnect();
};
});
}, []);
const newChildren = Children.map(children, (child, index) => {
return cloneElement(child, {
ref: (node: HTMLElement | null) => {
childRefs.current[index] = node;
},
className: toLeft
? isVisible[index]
? "hide-from-right fade-in-left"
: "hide-from-right"
: isVisible[index]
? "hide-from-left fade-in-right"
: "hide-from-left",
});
});
return <>{newChildren}</>;
};
export default FadeInChildren;
It needs to add ref to its child components.