Created
September 6, 2019 09:23
-
-
Save fedecarg/f59a1f92af2275f1754502d6eea93fb4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react'; | |
import PropTypes from 'prop-types'; | |
import throttle from 'lodash.throttle'; | |
import { Container, Placeholder } from './scroll-container.styles'; | |
const ScrollContainer = ({ children, mode, offsetTop }) => { | |
const [containerPosition, setContainerPosition] = useState('static'); | |
const [placeholderHeight, setPlaceholderHeight] = useState(null); | |
const placeholderRef = React.useRef(null); | |
const containerRef = React.useRef(null); | |
const handleScroll = () => { | |
if (window.pageYOffset >= offsetTop && containerPosition !== 'fixed') { | |
setPlaceholderHeight(containerRef.current.clientHeight); | |
setContainerPosition('fixed'); | |
} else if (window.pageYOffset < offsetTop && containerPosition === 'fixed') { | |
setPlaceholderHeight(0); | |
setContainerPosition('static'); | |
} | |
}; | |
useEffect(() => { | |
window.addEventListener('scroll', throttle(handleScroll, 200)); | |
return () => { | |
window.removeEventListener('scroll', throttle(handleScroll, 200)); | |
}; | |
}); | |
return ( | |
<> | |
<Placeholder minHeight={placeholderHeight} ref={placeholderRef} /> | |
<Container mode={mode} position={containerPosition} ref={containerRef}> | |
{children} | |
</Container> | |
</> | |
); | |
}; | |
ScrollContainer.propTypes = { | |
children: PropTypes.node.isRequired, | |
mode: PropTypes.oneOf(['light', 'dark', undefined]), | |
offsetTop: PropTypes.number, | |
}; | |
ScrollContainer.defaultProps = { | |
mode: undefined, | |
offsetTop: 0, | |
}; | |
export default ScrollContainer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment