Search code examples
javascripthtmlreactjstypescriptjavascript-objects

How to constantly return screen width/height in JavaScript?


I am trying to make a website responsive according to the screen width but using only javascript... So for that, I need a fucntion which constantly returns the screen width without stopping. Any solutions ??


Solution

  • I did not write this hook, but it is a very useful react hook for doing just what you are asking.

    import { useEffect, useState } from 'react'
    
    export function useWindowSize() {
      const [windowSize, setWindowSize] = useState({
        width: undefined,
        height: undefined
      })
    
      useEffect(() => {
        function handleResize() {
          setWindowSize({
            width: window.innerWidth,
            height: window.innerHeight
          })
        }
    
        window.addEventListener('resize', handleResize)
        handleResize()
    
        return () => window.removeEventListener('resize', handleResize)
      }, [])
    
      return windowSize
    }
    

    and you would call it in your react component like so:

    const windowSize = useWindowSize()
    

    EDIT
    here is a similar concept via vanilla JS

    function handleResize() {
      let newHeight = window.innerHeight;
      let newWidth = window.innerWidth;
      document.getElementById(
        "app"
      ).innerHTML = `width: ${newWidth}, height: ${newHeight}`;
    }
    
    window.addEventListener("resize", handleResize);
    // calling the function for the first time
    handleResize();
    

    you can also view a code sandbox of how the vanilla js example works: https://codesandbox.io/s/wild-cookies-n0ih6g?file=/src/index.js:0-308