useIntersectionObserver.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * <<
  3. * Davinci
  4. * ==
  5. * Copyright (C) 2016 - 2017 EDP
  6. * ==
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. * >>
  19. */
  20. import React, { useEffect, useState } from 'react'
  21. interface IntersectionObserverState {
  22. inView: boolean
  23. triggered: boolean
  24. entry: object
  25. }
  26. const defaultState: IntersectionObserverState = {
  27. inView: false,
  28. triggered: false,
  29. entry: null
  30. }
  31. export const useIntersectionObserver = (ref, { threshold, root, rootMargin }) => {
  32. const [state, setState] = useState<IntersectionObserverState>(defaultState)
  33. const observeInstance = new IntersectionObserver(
  34. (entries, instance) => {
  35. if (entries[0].intersectionRatio > 0) {
  36. setState({
  37. inView: true,
  38. triggered: true,
  39. entry: instance
  40. })
  41. observeInstance.unobserve(ref.current)
  42. }
  43. return
  44. },
  45. {
  46. threshold: threshold || 0,
  47. root: root || null,
  48. rootMargin: rootMargin || '0%'
  49. }
  50. )
  51. useEffect(() => {
  52. if (ref.current && !state.triggered) {
  53. observeInstance.observe(ref.current)
  54. }
  55. return () => {
  56. if (ref.current) {
  57. observeInstance.disconnect()
  58. }
  59. }
  60. }, [ref, state])
  61. return [state.inView, state.entry]
  62. }