Created
September 9, 2018 21:59
-
-
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)
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, { 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage:
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)