Skip to content

Instantly share code, notes, and snippets.

@tribou
Last active February 15, 2019 21:48
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tribou/d405436286807eeff669ad4d909331f5 to your computer and use it in GitHub Desktop.
Save tribou/d405436286807eeff669ad4d909331f5 to your computer and use it in GitHub Desktop.
Example React component that changes classes on scroll and supports passive event listeners where available
import React, { Component } from 'react'
import css from './Header.css'
class Header extends Component {
componentDidMount () {
this._bindScroll()
}
componentWillUnmount () {
this._unbindScroll()
}
_bindScroll = () => {
// Use passive event listener if available
let supportsPassive = false
try {
const opts = Object.defineProperty({}, 'passive', {
get: () => {
supportsPassive = true
},
})
window.addEventListener('test', null, opts)
}
catch (e) {} // eslint-disable-line no-empty
window.addEventListener(
'scroll',
this._handleScroll,
supportsPassive ? { passive: true } : false
)
}
_unbindScroll = () => {
window.removeEventListener('scroll', this._handleScroll)
}
_handleScroll = () => {
// Ugly cross-browser compatibility
const top = document.documentElement.scrollTop
|| document.body.parentNode.scrollTop
|| document.body.scrollTop
// Test < 1 since Safari's rebound effect scrolls past the top
if (top < 1) {
const className = `${header.header}`
this._header.className = className
}
else {
const className = `${header.header} ${header.scrolled}`
this._header.className = className
}
}
render () {
return (
<header
className={css.header}
ref={(ref) => {
this._header = ref
}}
>
</header>
)
}
}
export default Header
@b2whats
Copy link

b2whats commented Apr 10, 2017

Зачем все это - supportsPassive ? { passive: true } : false ? когда можно по дефолту всегда ставить этот параметр и браузер сам будет чекать поддерживается ли оно!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment