Skip to content

Instantly share code, notes, and snippets.

@AllanPooley
Created September 9, 2018 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AllanPooley/765631098d1736929fd3eac42939e6e6 to your computer and use it in GitHub Desktop.
Save AllanPooley/765631098d1736929fd3eac42939e6e6 to your computer and use it in GitHub Desktop.
Higher Order Component to track top and bottom position of an element (useful for elements that need to change when inside the viewport)
import React, { Component } from 'react';
import { isClient } from '../../config/app';
const scrollComponent = (WrappedComponent) => {
class ScrollComponent extends Component {
state = {
topPos: 0,
bottomPos: 0
};
componentDidMount() {
if (isClient) {
window.addEventListener('resize', this.updateDimensions);
setTimeout(() => {
this.updateDimensions();
}, 500);
}
}
componentWillUnmount() {
if (isClient) window.removeEventListener('resize', this.updateDimensions);
}
updateDimensions = () => {
const topPos = this.rootElement.getBoundingClientRect().top;
const bottomPos = this.rootElement.getBoundingClientRect().bottom;
this.setState({ topPos, bottomPos });
};
render() {
const { topPos, bottomPos } = this.state;
return (
<div className="scroll-container" ref={(rootElement) => { this.rootElement = rootElement; }}>
<WrappedComponent
{...this.props}
topPos={topPos}
bottomPos={bottomPos}
/>
</div>
);
}
}
return ScrollComponent;
};
export default scrollComponent;
@AllanPooley
Copy link
Author

AllanPooley commented Sep 9, 2018

Example usage:

import scrollComponent from '../ScrollComponent';

const SomeComponent = (props) => {
  // Component definition
}

const positionAwareElement = scrollComponent(SomeComponent);

export default positionAwareElement;

isClient is a conditional flag I use to check if the component is being rendered on the client or the server (React server-side rendering)

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