Reputation: 187
So I am feeling pretty dum to ask this but cannot find a straight answer to it.
Do I need to give any css parameter or directly to <Link>
in order for the pages on my react app open at the top?
EDIT
So refraining, everytime I click on a <Link>
element at my reactJs project, the Link opens a page at the middle of the screen, not a the top.
For example. I have this component
<li ><Link to={{pathname: "/product", state: {products}}}><i className="fa fa-search"></i></Link></li>
and when I click on in, it opens a new page/component but not at the top of the page. The user needs to scroll up in order to see the top, and i would like to open new pages directly at the top!
Upvotes: 0
Views: 3352
Reputation: 141
This worked for me... I created a function that will run after 10 nano-sec, i have tried without timer and making a use effect that will depend on path, but that didn't work for me...
const YourComponent = () => {
const scrollToTop = () => {
window.scrollTo(0, 0)
}
useEffect(() => {
const timerId = setTimeout(() => {
scrollToTop()
}, 10)
return () => clearTimeout(timerId)
}, [])
return (
<>
....
</>
)
}
Upvotes: 0
Reputation: 1
I am using the class component for my react blog. The issue got solved by adding the following method and calling it inside componentDidMount().
scrollToTop = () => {
window.scrollTo(0, 0)
}
componentDidMount() {
this.scrollToTop()
}
You can check this code is working. Live example, Blog.
If you are using a function component, then same method you can use and call it inside UseEffect().
Upvotes: 0
Reputation: 2605
make scrollToTop function and use it in your link tag
const scrollToTop = () => {
window.scrollTo(0, 0)
}
when user click on any link our function will make our page scroll to top.
<li onClick={scrollToTop} ><Link to={{pathname: "/product", state: {products}}}><i className="fa fa-search"></i></Link></li>
Upvotes: 0
Reputation: 93
This can be done without installing any additional libraries. You can check the official example of react-router
for scroll restoration here.
Upvotes: 2
Reputation: 365
You can use library react-scroll, and detect when change pathname of location, scroll to Top like this
import { animateScroll } from 'react-scroll';
useEffect(() => {
animateScroll.scrollToTop({
duration: 0
});
}, [location.pathname]);
Upvotes: 0