When you scroll to some position in the list and press "Space", new elements are prepended to the list. The code intention is to stay in the same scrolling view as before the user press "Space." Items are loaded and for some miliseconds, scroll view is in top of new prepended items and then scroll to saved previous scroll view. I want to make it instantly, without that miliseconds delay that is annoying for user.
Is it possible to get it?
CODE:
import React, { useState, useEffect, useRef } from "react";
import "./styles.css";
export default function App() {
const listRefs = useRef({});
const scrollRef = useRef();
const oldListHeight = useRef();
const generateId = (length) => {
let result = "";
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};
const generateList = () => {
const html = [];
for (let i = 0; i < Math.floor(Math.random() * 30) + 20; i++) {
const id = generateId(15);
listRefs.current[id] = React.createRef();
html.push(
<li ref={listRefs[id]} key={id}>
{id}
</li>
);
}
return html;
};
const [htmlList, setHtmlList] = useState(generateList());
useEffect(() => {
setTimeout(() => {
const listHeightDiff =
scrollRef.current.scrollHeight - oldListHeight.current;
scrollRef.current.scrollTo({
top: scrollRef.current.scrollTop + listHeightDiff
});
}, 0);
}, [htmlList]);
useEffect(() => {
window.addEventListener("keydown", handleKeyDown, false);
return () => {
window.removeEventListener("keydown", handleKeyDown, false);
};
}, []);
const handleKeyDown = (e) => {
if (e.key === " ") {
oldListHeight.current = scrollRef.current.scrollHeight;
setHtmlList((htmlList) => [generateList(), ...htmlList]);
}
};
return (
<div className="App">
<div ref={scrollRef} className="wrapper">
<ul>{htmlList}</ul>
</div>
</div>
);
}
PLAYGROUND:
https://codesandbox.io/s/affectionate-antonelli-wkvvd?file=/src/App.js
I think this is the issue,
Your setHtmlList((htmlList) => [generateList(), ...htmlList]);
generateList() returns an array so your array becomes [[some ids],oldids],
It becomes an array of arrays and React re-renders everything. What you need is [new ids,old ids].
To fix it I had to change the above line to
setHtmlList((htmlList) => [...generateList(), ...htmlList]);
Note the spread operator on generateList(). That will make the array flat and React can manage the rest.
Updated code,
https://codesandbox.io/s/eloquent-cherry-6hxyo?file=/src/App.js:1572-1633