Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

287
Vistas
Nested conditional

I'm trying to assign a value to a variable depending on the viewport size using Hooks in Gatsby I'm using nested conditionals and it works when I test the webpage for the first time but if I resize manually the window browser it displays the following error:

Rendered fewer hooks than expected. This may be caused by an accidental early return statement

As the react Docs says: Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. So I tried using a ternary operation:

let filter = (useMediaQuery({ query: '(max-width: 695px)' })) ? 2 : (useMediaQuery({ query: '(min-width: 900px)' })) ? 4 : 3

I also tried with:

if (useMediaQuery({ query: '(max-width: 695px)' })) 
 { filter = 2 } else if (useMediaQuery({ query: '(max-width: 900px)' })) 
 { filter = 4 } else { filter = 3 }

Could you help me, please?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

According to the rules of hooks, all hooks should be called at the top level of a component.

export function YourComponent() {
  const isSmallFormFactor = useMediaQuery({ query: '(max-width: 695px)' });
  const isMediumFormFactor = useMediaQuery({ query: '(max-width: 900px)' });

  const filter = isSmallFormFactor
    ? 2
    : isMediumFormFactor
    ? 4
    : 3;

  return (
    // ...
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda