Snippets Collections
function mediaQuery(element, value) {
  let x = document.querySelectorAll(element);

  x.forEach((item) => {
    if (window.matchMedia(`(max-width: ${value}px)`).matches) {
      item.classList.add('mobile');

    } else {
      item.classList.remove('mobile');
    }

  })

  return x;

}

// add class mobile to the element class hero on the screensize 600px
mediaQuery(".hero", 600);
import React, { useState, useEffect } from 'react';


const UseEffectCleanup = () => {
  
  const [width, setWidth] = useState(window.innerWidth);

  const checkSize = () => {
    setWidth(window.innerWidth)
  }

  useEffect(() => {

    window.addEventListener('resize', checkSize)
    return () => {
      window.removeEventListener('resize', checkSize)
    }
  }, [width]);

  return (
    <>
      <h1>Window Size</h1>
      <h2>{`${width}px`}</h2>
    </>
  );

}


export default UseEffectCleanup;
star

Tue Nov 01 2022 04:42:54 GMT+0000 (Coordinated Universal Time)

#media #query #mediaquery
star

Sat Oct 15 2022 23:34:47 GMT+0000 (Coordinated Universal Time)

#react #useeffect #mediaquery

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension