Skip to content

practical examle of using inview with mapped elements #586

Answered by mcgrealife
uyriq asked this question in Q&A
Discussion options

You must be logged in to vote

@uyriq here is an example #460

Basically create a Wrapper component that manages its own hook, and return the Wrapper in the map function

Edited based on @thebuilder reply:


const ParentComponent = () => {
// do not use the hook in parent! 

return (
  <div>
    ['your','data'].map((d, index) => (
      <Wrapper key={index} />
    ))
  </div>
)
}

// create a Wrapper component, use the hook here instead
const Wrapper = () => {
   const { ref, inView, entry } = useInView()
  
  useEffect(() => {
    inView && console.log('do something')
  },[inView])
  
  return (
  <div ref={ref}>
  The element that needs the refN
  </div>
  )
}

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@mcgrealife
Comment options

@thebuilder
Comment options

@mcgrealife
Comment options

Answer selected by thebuilder
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants