0

I'm trying to hide some components when the screen hits some specific breakpoint. My thought process was to store the screen width in a state then when it's below my breakpoint I set the display: none .

The question is how to access the screen width/viewport width in react? and is that the best approach for a responsive design?

  • Does this answer your question? [Get viewport/window height in ReactJS](https://stackoverflow.com/questions/36862334/get-viewport-window-height-in-reactjs) – amirify Aug 10 '21 at 19:17

2 Answers2

1

Here's a simple example

const useWindowWide = (size) => {
  const [width, setWidth] = useState(0)
  
  useEffect(() => {
    function handleResize() {
      setWidth(window.innerWidth)
    }
    
    window.addEventListener("resize", handleResize)
    
    handleResize()
    
    return () => { 
      window.removeEventListener("resize", handleResize)
    }
  }, [setWidth])
  
  return useWindowWidth > size
}

and to use it,

const Greeting = () => {
  const wide = useWindowWide(600)
  return (<h1>{wide ? "Hello World" : "Hello"}</h1>)
}

THere're quite a few hooks in the following reference might help you better.

  1. seWindowSize, https://usehooks.com/useWindowSize/
  2. useWindowSize, https://github.com/jaredLunde/react-hook/tree/master/packages/window-size
windmaomao
  • 5,431
  • 1
  • 26
  • 29
0

you can get width like this

const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)

But can go alone with CSS to hide certain things in breakpoints and make responsive designs

Nekromenzer
  • 145
  • 12