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

685
Visualizações
¿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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

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