This code was being used in my project which took the page to top whenever route changed and also when you click on a link of the same route you are on. I referred this answer to write the code below. The problem with the linked answer was that it didn't take the page to top if you click on a link which has the same route as you are on currently. So I modified it and wrote it like this.
import React, {useEffect} from 'react'
import { useLocation } from 'react-router-dom'
const Scroll2Top = () => {
const { pathname } = useLocation();
useEffect(() => {
window.scrollTo(0, 0);
});
return null;
}
export default Scroll2Top
But when I remove the useLocation
hook which is not even being used my code stops working. Why is this happening ?
Another similar example I came across is
// not being used but stops working if I remove this
let history = useNavigate();
useEffect(() => {
let termsInput = document.querySelector("#terms > input");
let claimInput = document.querySelector("#claim > input");
if (window.location.href.includes("#terms")) {
termsInput.checked = true;
claimInput.checked = false;
} else if(window.location.href.includes("#privacy")) {
termsInput.checked = false;
claimInput.checked = false;
}
else if (window.location.href.includes("#claim")) {
claimInput.checked = true;
termsInput.checked = false;
}
});
I have no clue why this happens and I was not able to find similar question anywhere on stackoverflow.