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

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