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

234
Visualizações
Maintain scroll position on expanding page with JavaScript

I am trying to maintain scroll position despite content being added to the top of the page, when you scroll to the top in a React app I am working on.

I have tried:

  • Getting the position of the top element on the page before the content is added and then using something like window.scrollTo(0, elementPosition)
  • Calculating the difference between the page height before and after the added content and scrolling back to the original position based on the difference.
  • Determining where to scroll based on how far the Viewport was from the bottom before the added content was displayed as that position should not be changing.

None of it worked and I am at a loss. This is the code that is responsible for creating the content, rendering a portion of the content and then adding content once you scroll to the top:

//Creating the content:

useEffect(() => {
    fetch('/api/endpoint', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    })
        .then(res => res.json())
        .then(res => {
            setLogUsers(res.users);
            setTotalAmount(res.log.length);
            setMessages(limitedRender(res.log));
        })
        .catch(err => console.log(err))
}, [renderAmount])

return(
    messages.map(e => {
        return(
            <Msg message = {e}/>
        );
    })
);

//Selecting a portion of the content and detecting when you scroll to the top:

const [totalAmount, setTotalAmount] = useState();
const [renderAmount, setRenderAmount] = useState(10);

const limitedRender = (arr) => {
  if (arr.length >= renderAmount) {
    return arr.slice(arr.length - (renderAmount), arr.length)
  }
  else {
    return arr
  }
}

const posTop = () => {
  return (
    typeof window.scrollY != 'undefined' ?  window.scrollY :
    document.documentElement && document.documentElement.scrollTop ?
    document.documentElement.scrollTop :
    document.body.scrollTop ? document.body.scrollTop : 0
  );
}

document.addEventListener('scroll', () => {
  if (posTop() === 0) {
    if (totalAmount - renderAmount >= 10) {
      setRenderAmount(renderAmount + 10);
    }
    else if (totalAmount - renderAmount < 10) {
      setRenderAmount(renderAmount + (totalAmount - renderAmount));
    }
  }
})

//Also may be important. I use this bit of code to ensure that the component stays scrolled to the bottom on initial render.

const btmUpView = () => {
    window.scrollTo(0, document.body.scrollHeight);
}

btmUpView();
return(
  <div>
    <div>
      <MsgFeed/>
    </div>
    <div>
      <input type="text"></input>
      <button onClick={() => sendMsg()}>Send</button>
    </div>
  </div>
);
about 4 years ago · Juan Pablo Isaza
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