Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typescript Version #3

Open
artokun opened this issue Jan 16, 2019 · 2 comments
Open

Typescript Version #3

artokun opened this issue Jan 16, 2019 · 2 comments

Comments

@artokun
Copy link

artokun commented Jan 16, 2019

import { useRef, useState, useEffect, RefObject } from 'react'
import 'intersection-observer'

type UseVisibilityType = (
  node: RefObject<any>,
  options?: IntersectionObserverInit | undefined
) => IntersectionObserverEntry | object

const useVisibility: UseVisibilityType = (node, options = {}) => {
  const [visible, setVisibilty] = useState({})
  const isIntersecting = useRef({})

  const handleObserverUpdate: IntersectionObserverCallback = entries => {
    const ent = entries[0]

    if (isIntersecting.current !== ent.isIntersecting) {
      setVisibilty(ent)
      isIntersecting.current = ent.isIntersecting
    }
  }

  const observer = new IntersectionObserver(handleObserverUpdate, options)

  useEffect(() => {
    const element = node.current

    if (!element) {
      return
    }

    observer.observe(element)

    return function cleanup() {
      observer.unobserve(element)
    }
  })

  return visible
}

export { useVisibility }
@artokun
Copy link
Author

artokun commented Jan 16, 2019

Once I am done with my current branch I'll share my tests

@AvraamMavridis
Copy link
Owner

@artokun feel free to open a PR if you feel like.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants