1) Want to apply "Intersection Observer" to 'lastElement'
2) useCallback as 'ref' to catch the 'lastelement'
3) Component Structure
- TotalPictureContainer
- SinglePicture { ref = useCallback(lastPictElementRef) }
- PictureContainer ( want to access here )
- SingleImage
Error
Error Happened
Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()
If we see the structure
We are accessing the element from 'child component' ( PictureContainer )
const SinglePicture = ({ Image , IsOdd = true}) => {
return (
<PictureContainer odd = {IsOdd} >
<SingleImage
src={Image.src}
alt={Image.alt}
initial='hidden'
animate='visible'
exit='exit'
odd = {IsOdd}
/>
</PictureContainer>
)
}
we can notice that ,
React components hide their implementation details, including their rendered output. Thus, components cannot easily access refs from their children.
But To access ref fromt children, React provides a feature called "Ref Forwarding."
Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.
So what we mean here is that ,
we have to let
component to access ref to its parent component
which is
So we change the code as below
const SinglePicture = forwardRef(({ Image , IsOdd = true}, ref) => {
return (
<PictureContainer odd = {IsOdd} ref = {ref}>
<SingleImage
src={Image.src}
alt={Image.alt}
initial='hidden'
animate='visible'
exit='exit'
odd = {IsOdd}
/>
</PictureContainer>
)
})
it is receiving 'ref' as parameter
and applying it to 'chld' component
so that it can access "ref" of its parent
component