Last active
January 17, 2019 17:01
-
-
Save tomduncalf/de95f7d902dfe257a96fccfd455be71d to your computer and use it in GitHub Desktop.
React Interaction Observer scroll
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
interface IState { | |
sticky: boolean; | |
} | |
export class HeaderBar extends React.Component<{}, IState> { | |
sentinelRef: React.RefObject<HTMLDivElement>; | |
observer: IntersectionObserver; | |
state = { sticky: false }; | |
constructor(props: IProps) { | |
super(props); | |
this.sentinelRef = React.createRef(); | |
} | |
componentDidMount() { | |
this.observer = new IntersectionObserver( | |
entries => | |
entries.forEach(entry => | |
this.setState({ sticky: entry.intersectionRatio !== 1 }) | |
), | |
{ threshold: 1 } | |
); | |
this.observer.observe(this.sentinelRef.current); | |
} | |
componentWillUnmount() { | |
if (typeof window === 'undefined') return; | |
this.observer.unobserve(this.sentinelRef.current); | |
} | |
render() { | |
const { sticky } = this.state; | |
return ( | |
<Container | |
sticky={sticky} | |
> | |
<Sentinel innerRef={this.sentinelRef} /> | |
<InnerContainerLeft fullHeight={fullHeightLeft}> | |
{left} | |
</InnerContainerLeft> | |
<InnerContainerRight>{right}</InnerContainerRight> | |
</Container> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment