How to perform a function by screen size javascript

Viewed 728

How to perform a function by screen size javascript/bootstrap?

this is the div : <div className="col-sm hidden-md hidden-lg"></div>

and i want to set this function (only in small screen) : const [ navOpen, setNavOpen ] = useState(true)

the code is in reactjs, how can i call a function when the screen is small?

3 Answers

I suspect you'd be much better off with a useEffect built around Window.matchMedia than something using innerWidth. This is the JavaScript equivalent of css media queries. That way you're using something event-driven.

Something like this maybe:

const [ navOpen, setNavOpen ] = useState(true)

useEffect(() => {
  const x = window.matchMedia("(max-width: 700px)")
  function myFunction(e) {
    setNavOpen(false);
  };
  x.addListener(myFunction)
  return () => x.removeListener(myFunction);
}, []);

Note: since it's got an event listener, note there is a clean up function being returned to remove the listener.

credit: I copied part of my code from w3schools

Edit: adding empty dependency array on recommendation of @agus-zubiaga

You can check for windows width and height in a useEffect and set your nav open or close for example.

useEffect({
    const width = windows.innerWidth;
    const height = windows.innerHeight;
    if(height <= 720 && width <= 420){
      setNavOpen(true)
    }
  }, [])

You can use window.innerHeight to calculate your useState default value:

const [ navOpen, setNavOpen ] = useState(window.innerWidth > 320)

However, if the Nav should open and close automatically when the screen is resized. You can use Window.matchMedia() which allows you to react to screen dimensions.

If this is a one-off, you can use it directly in a useEffect hook like in David784's answer.

In my case, since I work on a big app with many components that need to react to screen size, I use a library called react-responsive. It simplifies media queries in React.

Related