简体   繁体   中英

Stop react show more button scrolling to bottom of content

I have the follwing todo component. It's purpose is to show 10 todos, and when More is clicked, show 10 more.

const ToDoList = ({ todos }) => {
  const [viewCount, setViewCount] = useState(1);

  const handleViewMore = (e) => {
    setViewCount(viewCount + 1);
  };
  
  return (
    <div>
      <div>
        {
          todos.slice(0, viewCount * 10)
            .map((todo, index) => (
              <ToDo {...todo} key={index} />
            ))
        }
      </div>
      <button onClick={handleViewMore}>More</button>
    </div>
  );
};

The issue is when More is clicked, the extra todos are added however the windows scroll is still with the button, below the added todos.

For example, if 10 todos gives window.scrollY of 1000, when I click More , winodw.scrollY is now 2000, but I want it to remain at 1000 to allow the user to scroll through the next 10.

It's worth noting this does not happen if I change the button to an a or span .

Any ideas? Thanks!

Here is a codesandbox version of the issue - https://codesandbox.io/s/dry-snowflake-wl2h8?file=/src/App.js

I have included a More Broken button as well as a More Expected span. I'd like the button to behave as the span does.

That is strange, it is some new behavior that happens only in the latest version of chrome (85, maybe 84). All the other browsers remain the scroll position in your case. It might be a bug or a feature, not sure, meanwhile you can

change onClick to onMouseDown and

  const handleViewMore = (e) => {
    e.preventDefault()  
    setViewCount(viewCount + 1);
  };

You can use this:

useEffect(() => {
  window.scrollTo(0, 0)
}, [viewCount])

You could maitain the current scroll postion before click more button and scroll back to it

const [viewCount, setViewCount] = useState(1)
const [currentScrollTop, setCurrentScrollTop] = useState(0)

const handleViewMore = (e) => {
  setCurrentScrollTop(document.documentElement.scrollTop)
  setViewCount(viewCount + 1)
}

useEffect(() => {
  window.scrollTo(0, currentScrollTop)
}, [currentScrollTop])

Codesandbox link

编辑 elastic-flower-qtxv8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM