简体   繁体   中英

Change style of header component on scroll on home page only in React.Js

I have used the following approach to change the style of my header on scroll which is working fine. Referred this answer

  state = {
    scrolled: false
  };

  componentDidMount() {
    window.addEventListener('scroll', () => {
      const isTop = window.scrollY < 84
      if (!isTop) {
        this.setState({
          scrolled: true
        })
      } else {
        this.setState({
          scrolled: false
        })
      }
    })
  }

  componentWillUnmount() {
    window.removeEventListener('scroll')
  }

The problem is that it works on every route(component) as I have the header component included in the App.js file but I want it to work specifically on the Home page only.

Is there a way to check the current route and perform this transition on header, only for the home component which will work with my current approach or do I need to change my approach altogether?

You should create a method for handling scroll and refer it in both addEventListener and removeEventListener . But in your example, you are not referring it. You can use it like the below code sample.

And you should use a condition to match URL that works only on home page.


state = {
    scrolled: false
  };

  componentDidMount() {
    window.addEventListener('scroll', this.handleScroll);
  }
  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll);
  }

  handleScroll = () => {
    const isTop = window.scrollY < 84
    if (!isTop) {
      this.setState({
        scrolled: true
      })
    } else {
      this.setState({
        scrolled: false
      })
    }
  })

Hi you could use React Router's location for this use case and check in its pathName property where you are currently routed in your app.

Also be aware that binding function to scroll events can be very costly performance-wise -just add a console log and scroll and you'll see that it's being called a lot - and you'd like to prefer either another solution depending on what you're trying to achieve.

If you can't avoid passing a function to your scroll events you could use libraries such as RxJS or Lodash to debounce the function calls and avoid that it's being called too many times for nothing and potentially impact your performances.

https://www.learnrxjs.io/learn-rxjs/operators/filtering/throttle

https://www.learnrxjs.io/learn-rxjs/operators/filtering/debounce

https://lodash.com/docs/4.17.15#debounce

Depending on what you're trying to achieve you could also use the native Intersection Observer which is already optimised.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM