Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

121
Vistas
If I refresh the page matchMedia doesn't work

I'm using matchMedia in React to collapse my SideBar when the page is resizing. But the problem is if I refresh the page, my sidebar is open not closed. So if I want to collapse my SideBar I need to resize the page again or use the close button.

const layout = document.getElementById('home-layout');
const query = window.matchMedia('(max-width: 765px)');

  query.onchange = (evt) => {
      if( query.matches ) { 
        changeMenuMinified(true);
        layout.classList.add('extended-layout');
       } 
      else { 
        changeMenuMinified(false);
        layout.classList.remove('extended-layout');
      } 
    };
    query.onchange();
  };
  
  useEffect(() => {
    window.addEventListener('resize', handleResize);
  });

If I remove addEventListener it works, I can reload the page and my sidebar stays closed but if I try to open the sidebar with a button, the sidebar closes quickly

const handleResize = () => {

    const layout = document.getElementById('home-layout');
    const query = window.matchMedia('(max-width: 765px)');
    query.onchange = (evt) => {
      if( query.matches ) { 
        changeMenuMinified(true);
        layout.classList.add('extended-layout');
       } 
      else { 
        changeMenuMinified(false);
        layout.classList.remove('extended-layout');
      } 
    };
    query.onchange();
  };
  
  useEffect(() => {
    handleResize()
  });

  

sideBar

7 months ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

Some stuff to consider here:

  • Initialize your state with the current matching value
  • Remove listener on effect cleanup function
  • Don't forget the useEffect dependency array to avoid your code being executed on each render.

You can find a working example here -> https://codesandbox.io/s/stack-72619755-lpwh6m?file=/src/index.js:0-613

const query = window.matchMedia('(max-width: 765px)')

const App = () => {
  const [minified, changeMenuMinified] = useState(query.matches)

  useEffect(() => {
    const resizeHandler = () => {
      if (query.matches) {
        changeMenuMinified(true)
      } else {
        changeMenuMinified(false)
      }
    }

    query.addEventListener("change", resizeHandler);

    return () => query.removeEventListener("change", resizeHandler);
  })

  return <p>{minified ? 'minified' : 'expanded'}</p>
}

7 months ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos