React JS sticky navigation onScroll

10,054

Fixed by detecting when the window.scrollY position is at 0, like so:

handleScroll: function(event) {
  // Save the element we're wanting to scroll 
  var el = document.querySelector("#target");
  var pageY = window.scrollY
  //  If  we've scrolled past the height of the element, add a class
  if (el.getBoundingClientRect().bottom <= 0) {
    console.log(el.getBoundingClientRect().bottom + " bottom");
    this.setState({
      headerIsActive: true
    });
    //  If we've scrolled back up to  the top of the container, remove the class
  } else if (pageY == 0) {
    console.log("at top");
    this.setState({
      headerIsActive: false
    });
  }
},
Share:
10,054
A7DC
Author by

A7DC

Updated on June 04, 2022

Comments

  • A7DC
    A7DC almost 2 years

    I've created a React component here where I'm trying to get the header to become fixed after it has scrolled past itself. Everything works as expected in that instance, but after I've scrolled past the elements height, it switches the class on and off constantly.

    Here's the scroll function:

    handleScroll: function(event) {
      // Save the element we're wanting to scroll 
      var el = document.querySelector("#target");
      //  If  we've scrolled past the height of the element, add a class
      if (el.getBoundingClientRect().bottom <= 0) {
        console.log(el.getBoundingClientRect().bottom + " bottom");
        this.setState({
          headerIsActive: true
        });
        //  If we've scrolled back up to  the top of the container, remove the class
      } else if (el.getBoundingClientRect().top <= 0) {
        console.log(el.getBoundingClientRect().top <= 0 + " top");
        this.setState({
          headerIsActive: false
        });
      }
    },
    

    Can somebody please tell me what I'm doing wrong? Or point me in the right direction?

    Thanks