Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
cómo detectar que la ventana está cargada en reaccionar

He estado tratando de resolver este problema durante un par de días, pero parece que no puedo hacerlo funcionar.

Primero, tengo un enlace personalizado para obtener si el cliente está viendo en formato móvil o de escritorio.

que se parece a esto:

 import { useState, useEffect } from "react"; function getWindowDimensions() { if (typeof window !== "undefined") { const { innerWidth: width, innerHeight: height } = window; console.log("defined"); console.log(width < 768); return width < 768 ? true : false; } console.log("undefined"); return true; } export default function useWindowDimensions() { const [windowDimensions, setWindowDimensions] = useState( getWindowDimensions() ); function handleResize() { setWindowDimensions(getWindowDimensions()); } useEffect(() => { window.addEventListener("resize", handleResize); return () => window.removeEventListener("resize", handleResize); }, []); return windowDimensions; }

Ahora estoy tratando de usar esto para cambiar entre un pie de página o una interacción de estilo de encabezado en mi sitio web:

 import useWindowDimensions from "hooks/useWindowDimensions"; import React, { useEffect } from "react"; import Footer from "./Footer"; import Header from "./Header"; export default function Shim(props) { const isMobile = useWindowDimensions(); return ( <div> {!isMobile && <Header {...props} />} {isMobile && <Footer {...props} />} </div> ); }

Esperaba que esto funcionara perfectamente, sin embargo, parece que el valor inicial se establece cuando el tipo de ventana === "indefinido", por lo tanto, la vista móvil se muestra en tamaño de escritorio (si cambio el tamaño de la ventana después de cargar el sitio , funciona como se esperaba.) ¿Alguien estaría dispuesto a echarme una mano sobre cómo hacer que esto funcione correctamente?

¡Gracias!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Resuelvo el mismo problema con este contexto api hook.

 import React, { createContext, useContext, useEffect, useState } from 'react'; export const SizeContext = createContext(); const SizeContextProvider = ({ children }) => { const [width, setWidth] = useState(window.innerWidth); const [isMobile, setIsMobile] = useState(true); const [isDesktop, setIsDesktop] = useState(true); function debounce(fn, ms) { let timer; return () => { clearTimeout(timer); timer = setTimeout(() => { timer = null; fn.apply(this, arguments); }, ms); }; } useEffect(() => { const debouncedHandleResize = debounce(() => { setWidth(window.innerWidth); }, 0); window.addEventListener('resize', debouncedHandleResize); return () => { window.removeEventListener('resize', debouncedHandleResize); }; }); useEffect(() => { if (width <= 575) { setIsMobile(true); setIsDesktop(false); } else if (width >= 576 && width < 767) { setIsMobile(true); setIsDesktop(false); } else if (width >= 768 && width < 991) { setIsMobile(false); setIsDesktop(true); } else if (width >= 992 && width < 1199) { setIsMobile(false); setIsDesktop(true); } else { setIsMobile(false); setIsDesktop(true); } }, [width]); return ( <SizeContext.Provider value={{ width, isDesktop, isMobile }}> {children} </SizeContext.Provider> ); }; export const useSizeContext = () => useContext(SizeContext); export default SizeContextProvider;

importar contexto api usar cualquier componente.

 const App = () => { return ( <SizeContextProvider> <Device /> </SizeContextProvider> ) }

Aquí el componente del dispositivo usa Context Api

 const Device = () => { const { isMobile, isDesktop } = useSizeContext(); return ( <div> {isMobile && <h1> Small Device </h1>} {isDesktop && <h1> Largest Device </h1>} </div> ); }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!