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

160
Visualizações
React matchMedia - is there a cleaner way to do this?

I need to render different components based on the screen size -

If the screen is 1012px or under then setComponent('box');

If the screen is 1460px or under then setComponent('info);

Else if the screen is above 1460px then setComponent('both');

This is how I'm currently doing it -

  if (typeof window !== 'undefined' && showComponents) {
    window.matchMedia('(max-width: 1012px)').addEventListener('change', (event) => {
      if (event.matches) {
        setComponent('box');
      }
    });

    window.matchMedia('(max-width: 1460px)').addEventListener('change', (event) => {
      if (event.matches) {
        setComponent('info');
      }
    });

    window.matchMedia('(min-width: 1460px)').addEventListener('change', (event) => {
      if (event.matches) {
        setComponent('both');
      }
    });
  }

Before this, I was using window.innerWidth however I read that matchMedia is a better solution to this. But looking at the code above, I am not sure if there is a cleaner way of writing it. Also do the listeners need to be removed?

about 4 years ago · Santiago Gelvez
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