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

246
Visualizações
How to access client-side window method in Next.js

I am trying to change the structure of my app using DOM media queries inside Next.js. Normal media queries (CSS) work no problem. In "pure" React, I could do something like this:

function HomePage () {
  const [landscape, setLandscape] =  useState(false)

  useEffect(() => {

    const landscapeHandler = e => {
      console.log ("Change in landscape")
      setLandscape({matches: e.matches});
    }
   
    window.matchMedia("((orientation:landscape)").addEventListener('change', landscapeHandler);

    return () => {
      window.removeEventListener('change', landscapeHandler);
    }


}, [])
}

However, when using Next, changing the orientation of the screen doesn't do anything at all. Is there a workaround? I always thought useEffect is client-side only and therefore the right place to do such media queries... Many thanks in advance!

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

0

Next.js executes the code first in the server and then in the client. So, when it executes in server, window would be undefined.

You can do it like the code below,

 useEffect(() => {
   
    if (typeof window !== "undefined") {
     window.matchMedia("((orientation:landscape)").addEventListener('change', landscapeHandler);
    }
    // component Will Unmount
    return () => {
      if (typeof window !== "undefined") {
        window.removeEventListener('change', landscapeHandler);
      }
    };
  }, []);

about 4 years ago · Juan Pablo Isaza Relatório

0

You could have used 'orientationchanged' listener, but I think it's depreciated.

You can try using the 'resize' listener.

 useEffect(() => {

    const handleChange = () => {
      

      const width = document.documentElement.clientWidth
      const height = document.documentElement.clientHeight
      
      const orientation = width > height ? 'landscape' : 'portrait';

      console.log('orientation: ', orientation, 'width', width, 'height', height)

    }
    if (typeof window !== 'undefined') {
        const unsub = window.addEventListener('resize', handleChange)
        return () => unsub();
    }

  },[])
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