Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
Cómo acceder al método de ventana del lado del cliente en Next.js

Estoy tratando de cambiar la estructura de mi aplicación usando consultas de medios DOM dentro de Next.js. Las consultas de medios normales (CSS) funcionan sin problemas. En React "puro", podría hacer algo como esto:

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

Sin embargo, al usar Siguiente, cambiar la orientación de la pantalla no hace nada en absoluto. ¿Hay una solución? Siempre pensé que useEffect es solo del lado del cliente y, por lo tanto, el lugar correcto para hacer tales consultas de medios... ¡Muchas gracias de antemano!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Next.js ejecuta el código primero en el servidor y luego en el cliente. Entonces, cuando se ejecuta en el servidor, la ventana no estaría definida.

Puedes hacerlo como el siguiente código,

 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 Report

0

Podrías haber usado el oyente 'orientationchanged', pero creo que está depreciado.

Puede intentar usar el oyente 'cambiar tamaño'.

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!