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

686
Vistas
¿Cómo detectar el tamaño de la ventana en Next.js SSR usando el gancho de reacción?

Estoy creando una aplicación usando Next.js y react-dates .

Tengo un componente DateRangePicker de dos componentes y un componente DayPickerRangeController .

Quiero renderizar DateRangePicker cuando el ancho de la ventana es mayor que el tamaño de 1180px, si el tamaño es más pequeño que esto, quiero renderizar DayPickerRangeController en su lugar.

Aquí está el código:

 windowSize > 1180 ? <DateRangePicker startDatePlaceholderText="Start" startDate={startDate} startDateId="startDate" onDatesChange={handleOnDateChange} endDate={endDate} endDateId="endDate" focusedInput={focus} transitionDuration={0} onFocusChange={(focusedInput) => { if (!focusedInput) { setFocus("startDate") } else { setFocus(focusedInput) } }} /> : <DayPickerRangeController isOutsideRange={day => isInclusivelyBeforeDay(day, moment().add(-1, 'days'))} startDate={startDate} onDatesChange={handleOnDateChange} endDate={endDate} focusedInput={focus} onFocusChange={(focusedInput) => { if (!focusedInput) { setFocus("startDate") } else { setFocus(focusedInput) } }} /> }

Normalmente uso el gancho de reacción con el objeto de la ventana para detectar el ancho de la pantalla de la ventana como este

Pero descubrí que esta forma no está disponible cuando ssr porque la representación de ssr no tiene un objeto de ventana.

¿Hay alguna forma alternativa de obtener el tamaño de la ventana de forma segura independientemente de ssr?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Puede evitar llamar a su función de detección en ssr agregando este código:

 // make sure your function is being called in client side only if (typeof window !== 'undefined') { // detect window screen width function }

ejemplo completo de su enlace:

 import { useState, useEffect } from 'react'; // Usage function App() { const size = useWindowSize(); return ( <div> {size.width}px / {size.height}px </div> ); } // Hook function useWindowSize() { // Initialize state with undefined width/height so server and client renders match // Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/ const [windowSize, setWindowSize] = useState({ width: undefined, height: undefined, }); useEffect(() => { // only execute all the code below in client side if (typeof window !== 'undefined') { // Handler to call on window resize function handleResize() { // Set window width/height to state setWindowSize({ width: window.innerWidth, height: window.innerHeight, }); } // Add event listener window.addEventListener("resize", handleResize); // Call handler right away so state gets updated with initial window size handleResize(); // Remove event listener on cleanup return () => window.removeEventListener("resize", handleResize); } }, []); // Empty array ensures that effect is only run on mount return windowSize; }
over 4 years ago · Santiago Trujillo Denunciar

0

Mientras que Darryl RN ha proporcionado una respuesta absolutamente correcta. Me gustaría hacer un pequeño comentario: realmente no es necesario verificar la existencia del objeto de window dentro useEffect porque useEffect solo se ejecuta en el lado del cliente y nunca en el lado del servidor, y el objeto de la window siempre está disponible en el cliente. -lado.

over 4 years ago · Santiago Trujillo Denunciar

0

useEffect(()=> { window.addEventListener('resize', ()=> { console.log(window.innerHeight, window.innerWidth) }) }, [])
over 4 years ago · Santiago Trujillo Denunciar
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