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

564
Visualizações
NextJS: ¿Cómo hago para que este componente muestre el ancho en la carga de la página?

Cuando ejecuto el siguiente código que obtiene el ancho de pantalla del navegador, aparece este error:

ReferenceError: la ventana no está definida

El código comentado funciona, usa 0 como valor predeterminado, pero se actualiza correctamente cuando se cambia el ancho del navegador.

Obtengo el error de que la ventana no está definida o paso un número predeterminado al estado, que muestra el ancho incorrecto en la carga de la página.

¿Cómo defino window.innerWidth al cargar la página?

 import React, { useState, useEffect } from "react"; const WindowTracker = () => { const [show, setShow] = useState(true); // const [windowWidth, setWindowWidth] = useState(0); const [windowWidth, setWindowWidth] = useState(window.innerWidth); const triggerToggle = () => { setShow(!show); }; useEffect(() => { function watchWidth() { setWindowWidth(window.innerWidth); } window.addEventListener("resize", watchWidth); return function () { window.removeEventListener("resize", watchWidth); }; }, []); return ( <div> <button onClick={triggerToggle}>Toggle WindowTracker</button> {show && <h1>Window width: {windowWidth}px</h1>} </div> ); // } }; export default WindowTracker;

¡Gracias!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Usa este gancho:

 const [windowWidth, setWindowWidth] = useState(); useEffect(() => { setWindowWidth(window.innerWidth) }, [window.innerWidth])

about 4 years ago · Juan Pablo Isaza Relatório

0

Esto sucede porque en el renderizado previo que realiza nextjs en el servidor de ventanas aún no está definido, resolví esto en mi código agregando un si, este es un código de ejemplo de cómo se vería

 import React, { useState, useEffect } from "react"; const WindowTracker = () => { const [show, setShow] = useState(true); // const [windowWidth, setWindowWidth] = useState(0); const [windowWidth, setWindowWidth] = useState(typeof window !== "undefined" ? window.innerWidth : 0); const triggerToggle = () => { setShow(!show); }; useEffect(() => { if (typeof window !== "undefined") { function watchWidth() { setWindowWidth(window.innerWidth); } window.addEventListener("resize", watchWidth); return function () { window.removeEventListener("resize", watchWidth); }; } }, []); return ( <div> <button onClick={triggerToggle}>Toggle WindowTracker</button> {show && <h1>Window width: {windowWidth}px</h1>} </div> ); // } }; export default WindowTracker;
about 4 years ago · Juan Pablo Isaza Relatório

0

Debe activar setWindowWidth cuando el componente se montó

 const isClientSide = () => typeof window !== 'undefined'; const getWindowSize = () => { if (isClientSide()) return window.innerWidth return 0 } const WindowTracker = () => { const [show, setShow] = useState(true); const [windowWidth, setWindowWidth] = useState(getWindowSize()); const triggerToggle = () => { setShow(!show); }; useEffect(() => { function watchWidth() { setWindowWidth(window.innerWidth); } window.addEventListener("resize", watchWidth); setWindowSize(getWindowSize()); <=== This should set the right width return function () { window.removeEventListener("resize", watchWidth); }; }, []); return ( <div> <button onClick={triggerToggle}>Toggle WindowTracker</button> {show && <h1>Window width: {windowWidth}px</h1>} </div> ); }; export default WindowTracker;
about 4 years ago · Juan Pablo Isaza 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