0

// import { useState } from 'react' import Res from './responsiveMenu/Res' import NormalWidth from './navNormalwidth/NormalWidth'

const Navbar=()=>{ const [click,setClick]=useState(true)

// function to change from true to false const navBtn=()=>{setClick(!click)}

const screenwidth=window.innerWidth

return(

<>
{screenwidth<'640' ? <Res btnF={navBtn} click={click}/>:screenwidth>'640'?<NormalWidth/>:''}
  
</>

)

}

export default Navbar

why when the screen is 640 is works but when i make it bigger i the menu btn stays until i press it then it will render the normal component

  • You would need to either listen for the window resize event, or use a ResizeObserver. Then update the width variable. – DBS Jan 09 '23 at 10:06
  • 1
    Does this answer your question? [Rerender view on browser resize with React](https://stackoverflow.com/questions/19014250/rerender-view-on-browser-resize-with-react) – DBS Jan 09 '23 at 10:07

2 Answers2

0

Please use the viewport unit with width.

eg:

width:100vw;
Naeem Ahmed
  • 216
  • 1
  • 6
  • This is used for styling with css. But in the shared code he wants to conditionally render a different button based on the current window width. So he either needs to use css `media queries` to hide or show the button via css or as mentioned in my answer observe the window width to cause rerendering of the component. – peetzweg Jan 09 '23 at 10:36
0

As mentioned in the comments, your component does NOT rerender when the window size is changing. You need to register a listener, which updates the a react state which causes your component to rerender. State of the art would be to create this via a hook. As this is a very common functionality people already implemented examples of such a hook for you.

You can find a good one here. Not library needed.

https://usehooks.com/useWindowSize/

If you are not yet familiar with using hooks, the official React documentation is very good.

https://reactjs.org/docs/hooks-intro.html

peetzweg
  • 63
  • 4