Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
Delay after prepending elements to a list and scroll to same scrolling view

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda