React - check if element is visible in DOM

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

    I have had the same problem, and, looks, I found the pretty good solution in pure react jsx, without installing any libraries.

    import React, {Component} from "react";
        
        class OurReactComponent extends Component {
    
        //attach our function to document event listener on scrolling whole doc
        componentDidMount() {
            document.addEventListener("scroll", this.isInViewport);
        }
    
        //do not forget to remove it after destroyed
        componentWillUnmount() {
            document.removeEventListener("scroll", this.isInViewport);
        }
    
        //our function which is called anytime document is scrolling (on scrolling)
        isInViewport = () => {
            //get how much pixels left to scrolling our ReactElement
            const top = this.viewElement.getBoundingClientRect().top;
    
            //here we check if element top reference is on the top of viewport
            /*
            * If the value is positive then top of element is below the top of viewport
            * If the value is zero then top of element is on the top of viewport
            * If the value is negative then top of element is above the top of viewport
            * */
            if(top <= 0){
                console.log("Element is in view or above the viewport");
            }else{
                console.log("Element is outside view");
            }
        };
    
        render() {
            // set reference to our scrolling element
            let setRef = (el) => {
                this.viewElement = el;
            };
            return (
                // add setting function to ref attribute the element which we want to check
                
    {/*some code*/}
    ); } } export default OurReactComponent;

    I was trying to figure out how to animate elements if the are in viewport.

    Here is work project on CodeSandbox.

提交回复
热议问题