React - check if element is visible in DOM

前端 未结 5 2009
刺人心
刺人心 2020-12-25 12:24

I\'m building a form - series of questions (radio buttons) the user needs to answer before he can move on to the next screen. For fields validation I\'m using yup (npm packa

5条回答
  •  孤城傲影
    2020-12-25 12:43

    Here is a reusable hook that takes advantage of the IntersectionObserver API.

    The hook

    export default function useOnScreen(ref) {
    
      const [isIntersecting, setIntersecting] = useState(false)
    
      const observer = new IntersectionObserver(
        ([entry]) => setIntersecting(entry.isIntersecting)
      )
    
      useEffect(() => {
        observer.observe(ref.current)
        // Remove the observer as soon as the component is unmounted
        return () => { observer.disconnect() }
      }, [])
    
      return isIntersecting
    }
    

    Usage

    const DummyComponent = () => {
      
      const ref = useRef()
      const isVisible = useOnScreen(ref)
      
      return 
    {isVisible && `Yep, I'm on screen`}
    }

提交回复
热议问题