Created
May 28, 2019 16:41
-
-
Save jonahallibone/0630f5763af50c836496607fa16e526e to your computer and use it in GitHub Desktop.
Hook for scroll to top
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, { useEffect, useRef } from "react"; | |
import { withRouter } from 'react-router-dom'; | |
function usePrevious(value) { | |
const ref = useRef(); | |
useEffect(() => { | |
ref.current = value; | |
}) | |
return ref.current; | |
} | |
const ScrollToTop = (props) => { | |
const { location } = props; | |
const prevProps = usePrevious({location}); | |
useEffect(() => { | |
if(!prevProps) return; | |
if (location.pathname !== prevProps.location.pathname) { | |
window.scrollTo(0, 0); | |
} | |
}, [location]); | |
return ( | |
<div></div> | |
) | |
} | |
export default withRouter(ScrollToTop); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment