Darren
Darren

Reputation: 2290

Adding a className on scroll?

How can I add a className when the page scrolls? I have ready many other articles and answers to this (may be a duplicate) but none have helped me understand what is wrong with my code below.

If the code is not the issue I believe that it stems from a perspective wrapper around the app that may disallow the registration of scroll. How can I add the event listener to register scroll on id=container

constructor(props) {
  super(props)
  this.state = {
      isStuck: true,
  }
this.handleHeaderStuck = this.handleHeaderStuck.bind(this)
}

componentDidMount () {
  window.addEventListener('scroll', this.handleHeaderStuck);
}

componentWillUnmount () {
  window.removeEventListener('scroll', this.handleHeaderStuck);
}

handleHeaderStuck() {
  if (window.scrollY === 0 && this.state.isStuck === true) {
      this.setState({isStuck: false});
  }
  else if (window.scrollY !== 0 && this.state.isStuck !== true) {
      this.setState({isStuck: true});
  }
}

render() {

  return (
    <main className={this.state.isStuck ? 'header-stuck' : ''}>
       ...
    </main>

enter image description here

This screenshot reassures me that the issue is with the registering of onScroll listener

Upvotes: 0

Views: 65

Answers (2)

Andrii Starusiev
Andrii Starusiev

Reputation: 7764

Be sure your component have enough height for scroll. Your code works. Add some height to main and check it.

main {
  height: 2000px;
}

https://jsfiddle.net/69z2wepo/156204/

enter image description here

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281726

You code has an issue, onScroll is attached a listener function handleScroll whereas the function is handleHeaderStuck in your case. Change the listener to execute the correct function.

componentDidMount () {
  window.addEventListener('scroll', this.handleHeaderStuck);
}

componentWillUnmount () {
  window.removeEventListener('scroll', this.handleHeaderStuck);
}

Upvotes: 1

Related Questions