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?
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; }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.
useEffect(()=> { window.addEventListener('resize', ()=> { console.log(window.innerHeight, window.innerWidth) }) }, [])