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

288
Visualizações
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 Respostas
Responde à pergunta

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 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