Use function composition to hide implementation details
Reaction 16.8 + functional component
useScroll hook
The following useScroll hook hides the details of the dom implementation and provides a simple API.
const useScroll = () => { const htmlElRef = useRef(null) const executeScroll = () => { window.scrollTo(0, htmlElRef.current.offsetTop) } return [executeScroll, htmlElRef] }
Then you can easily scroll through your functional components.
const ScrollDemo = () => { const [executeScroll, elementToScrollRef] = useScroll() return ( <> <div ref={elementToScrollRef}>I wanna be seen</div> <button onClick={executeScroll}> Click to scroll </button> </> ) }
Click here for a full demo on StackBlitz
Responsive 16.3 + Grade Component
utilizeScroll
The compositioin function can also be used in class components.
const utilizeScroll = () => { const htmlElRef = React.createRef() const executeScroll = () => { window.scrollTo(0, htmlElRef.current.offsetTop) } return {executeScroll, htmlElRef} }
Then use it in any component of the class
class ScrollDemo extends Component { constructor(){ this.elScroll = utilizeScroll() } render(){ return ( <> <div ref={this.elScroll.htmlElRef}>I wanna be seen</div> <button onClick={this.elScroll.executeScroll} >Click to scroll </button> </> ) } }
Click here for a full demo on StackBlitz
Ben carp
source share