2

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?

1
  • Window.matchMedia might be a good option for this. Commented Mar 22, 2020 at 17:42

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I agree. However, I think this code has a bug. If the user manually opened the nav, and their screen matches the media query, this hook will immediately close it because it runs on every render. I would pass an empty dependency array.
1

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)
    }
  }, [])

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.