¿Hay alguna forma de acceder al ancho o alto del dispositivo en React o Next.js sin usar "ventana"? o "documento". Entiendo que podemos obtener esto con el gancho useEffect y no tenemos este error:
ReferenceError: window is not definedpero eso es una exageración si solo necesito acceder al ancho una vez
import { useEffect, useState } from "react"; const LayoutContainer = ({ Component, pageProps }) => { const [mobile, setMobile] = useState(true); useEffect(() => { console.log(window.innerWidth < 450, window.innerWidth); setMobile(window.innerWidth); return () => setMobile(window.innerWidth < 450); }, [window.innerWidth]); //ReferenceError: window is not defined return ( <> <Header /> <Component {...pageProps} /> <Footer mobile={mobile} /> </> ); }; export default LayoutContainer;Yo usaría window.matchMedia pero, en cambio, agregaría un detector de eventos en useEffect y eliminaría la dependencia de la window , así:
const { useState, useEffect } = React; const Example = () => { const [isWide, setIsWide] = useState(null); useEffect(() => { const mql = window.matchMedia("(min-width: 768px)"); const onChange = () => setIsWide(!!mql.matches); mql.addListener(onChange); setIsWide(mql.matches); return () => mql.removeListener(onChange); }, []); return <div>Is Wide: {isWide ? "true" : "false"}</div>; }; ReactDOM.render(<Example />, document.getElementById("root")); <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div>Inspirado en https://github.com/streamich/react-use/blob/master/src/useMedia.ts
Si está buscando eliminar completamente su useEffect , supuse que podría hacer algo como esto si solo necesita encontrar el ancho una vez en el montaje:
let isMobile = null; if (typeof window !== "undefined") { isMobile = window.innerWidth < 450; } console.log(isMobile);