Skip to content

Instantly share code, notes, and snippets.

@tomduncalf
Last active January 17, 2019 17:01
Show Gist options
  • Save tomduncalf/de95f7d902dfe257a96fccfd455be71d to your computer and use it in GitHub Desktop.
Save tomduncalf/de95f7d902dfe257a96fccfd455be71d to your computer and use it in GitHub Desktop.
React Interaction Observer scroll
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