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

157
Visualizações
Not been able to read the value of scrollY

I have been trying to read the value of scrollY (chrome Version 96.0.4664.45 (Official Build) (64-bit)). But it does not seems to work. Here is my code :

import React from "react";

import{useEffect, useState} from "react"


 
export default function Test() {
  const [offset, setOffset] = useState(0);
  const setScroll = () => {
    setOffset(window.scrollY);
  };

    useEffect(() => {
    window.addEventListener("scroll", setScroll);
    return () => {
      window.removeEventListener("scroll", setScroll);
    };
  }, []);

  return (
    <div className="App" style={{ height: "1000px" }}>
      <h1>Hello CodeSandbox</h1>
      <div>{offset}</div>
      
    </div>
  );
}

Here is a picture of the output: enter image description here

enter image description here

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

0

Here is the same code you provided in your question in a snippet (it works). I simply changed the scroll event target from window to document. See the MDN page for the document scroll event: https://developer.mozilla.org/en-US/docs/Web/API/Document/scroll_event

<div id="root"></div><script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.16.4/babel.min.js"></script>
<script type="text/babel" data-type="module" data-presets="react">

const {useEffect, useState} = React;

function Test () {
  const [offset, setOffset] = useState(0);
  const setScroll = () => setOffset(window.scrollY);

  useEffect(() => {
    document.addEventListener("scroll", setScroll);
    return () => document.removeEventListener("scroll", setScroll);
  }, []);

  return (
    <div style={{ height: "1000px" }}>
      <h1>Hello CodeSandbox</h1>
      <div style={{ position: 'sticky', top: '1rem' }}>{offset}</div>
    </div>
  );
}

ReactDOM.render(<Test />, document.getElementById('root'));

</script>

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