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.
Advertisement
Answer
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); };