Every time you perform a render in React.js, the UI scrolls to the top of the page.
JSFiddle: http://jsfiddle.net/bengrunfeld/dcfy5xrd/
Any nifty or reactive way to stop that?
E.g. If a User scrolls down the page, then pushes a button which causes a Render, the UI would stay in the same scroll location as before.
// Forces a render which scrolls to top of page this.setState({data: data});
UPDATE: Why does the UI scroll to the top for some renders, but not others?
2022 Hacky Solution: useEffect(() => { const el = document. getElementsByClassName('my-classname')?.[0]; const newTimeoutRef = setTimeout(() => el?. scrollTo(0, scrollTop), 50); return () => clearTimeout(newTimeoutRef); }, [scrollTop]);
To prevent scrolling using CSS on React rendered components, we can set the overflow CSS property to hidden with JavaScript. to set the overflow CSS of the body element to hidden when the component mounts with: document. body.
To get scroll position with React, we can add a scroll listener to window . to create the scrollPosition state with the useState hook. Then we add the handleScroll function that takes the scroll position with the window.
In this article, we’ll look at how to prevent scrolling using CSS on React rendered components. To prevent scrolling using CSS on React rendered components, we can set the overflow CSS property to hidden with JavaScript. The useEffect callback only runs when the component mounts since we passed in an empty array as the 2nd argument of useEffect.
Create top level component to manage the scroll Now let’s create a component as ScrollToTop where we will listen to the history and set window scroll to top on componentDidMount. You can also ignore the routes for scroll to the top as well. Here we are using the React Hooks to manage the scroll position.
If render trigger scrolling to the top it usually means some UI component is changing its dimension because of the state, this can be fixed by adding a minimum width/height Thanks for contributing an answer to Stack Overflow!
If a User scrolls down the page, then pushes a button which causes a Render, the UI would stay in the same scroll location as before. UPDATE: Why does the UI scroll to the top for some renders, but not others?
Ok if anyone read this , in my case the problem wasn't any of above. You must try first suggestions on above any way. I did everything including preventDefault()
but didn't help me. The problem was ; using styled-components
. Because, styled-components give a random classname every render. So it resets scroll. I gave the class name from css and solved my problem.
@floydophone answered this one on Twitter.
https://twitter.com/floydophone/status/608129119025561600
@bengrunfeld @reactjs you forgot
preventDefault()
on your link handlers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With