Skip to content

Instantly share code, notes, and snippets.

@fedecarg
Created September 6, 2019 09:23
Show Gist options
  • Save fedecarg/f59a1f92af2275f1754502d6eea93fb4 to your computer and use it in GitHub Desktop.
Save fedecarg/f59a1f92af2275f1754502d6eea93fb4 to your computer and use it in GitHub Desktop.
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