Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

230
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda