I have problem with scroll to top after rerender component. Is there any way to prevent this ? I dont want to scroll to top after any rerender just change the content.
I have problem with scroll to top after rerender component. Is there any way to prevent this ? I dont want to scroll to top after any rerender just change the content.
This may not be the best way of doing it in React, but it should work.
As described in this page, there is a way to get the amount of pixels the user scrolled and store them in a variable. Then use that value to programmatically change the amount of scrolled pixels after the rerender. This is for Javascript, but it should also work for React.
Simple Example:
// Get the scroll pixels from the top of the page (Store this before rerender)
const scrollFromTop = document.documentElement.scrollTop;
// Update the scroll pixels from the top of the page with the stored int value (Do this after rerender)
document.documentElement.scrollTop = scrollFromTop;
you can give your component a state,
import React, {useState, useEffect} from 'react';
const MyComponent = props => {
const [scrolled, setScrolled] = useState(false);
useEffect(() => {
if (scrolled) {
return; // no more scrolling
}
setScrolled(true);
// TODO: scroll to top here
}, [scrolled]);
// ...
};
export default MyComponent;