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?

2
  • Does this answer your question? Get viewport/window height in ReactJS Commented Aug 10, 2021 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. Commented Aug 18, 2022 at 10:08

3 Answers 3

7

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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>

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.