ChungHa Brocher_1 : 2021.04.30 React.forwardRef

5794 단어 ReactReact

Error

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 )

But if we see the 'code of 'child component'

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 ,

it is not receiving any 'ref's

What do we have to do ??

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

PictureContainer

component to access ref to its parent component
which is

SinglePicture

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>
  )
})

As we can see

it is receiving 'ref' as parameter
and applying it to 'chld' component

so that it can access "ref" of its parent
component

좋은 웹페이지 즐겨찾기