2

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?

Mahmoud Ali
  • 116
  • 2
  • 2
  • 10
  • 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
  • Using CSS media queries is an easy solution. It detects the breakpoints for you and applies the correct styles when the conditions get satisfied. – Uzair_07 Aug 18 '22 at 10:08

3 Answers3

4

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
  • 7,120
  • 2
  • 32
  • 36
1

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
  • 334
  • 2
  • 16
1

Only correcting something that went wrong to me in the preview answer. This way worked for me:

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 width

}

const wide = useWindowWide(400)
<h1>{wide >= 500 ? "Desktop" : "Mobile"}</h1>