React - check if element is visible in DOM

前端 未结 5 2041
刺人心
刺人心 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:28

    You can attach a ref to the element that you want to check if it is on the viewport and then have something like:

      /**
       * Check if an element is in viewport
       *
       * @param {number} [offset]
       * @returns {boolean}
       */
      isInViewport(offset = 0) {
        if (!this.yourElement) return false;
        const top = this.yourElement.getBoundingClientRect().top;
        return (top + offset) >= 0 && (top - offset) <= window.innerHeight;
      }
    
    
      render(){
    
         return(
    this.yourElement = el}> ...
    ) }

    You can attach listeners like onScroll and check when the element will be on the viewport.

    You can also use the Intersection Observer API with a polyfil or use a HoC component that does the job

提交回复
热议问题