React conditionally render based on viewport size

后端 未结 4 2045
太阳男子
太阳男子 2021-01-30 11:24

This should be an easy one for you React monsters. :) I have the condition written but I can\'t figure out how to handle the viewport size in my constructor for the condition to

4条回答
  •  粉色の甜心
    2021-01-30 12:09

    the issue with your code is that it only works if the resizing happens, here I have the handleWindowResiz function will set the width to the window.innerWidth and compares it to the breakPoint to conditionally render your UI, if the user resizes the screen the event listener will be triggered and the handleWindowResiz will be called and it will reset the width to the new window.innerWidth and you get your desired UI. So the UI is always rendered correctly when the component is first rendered and when the user resizes the screen width.

    const MyFunction = () => {
    
      const [width, setWidth] = React.useState(window.innerWidth);
      const breakPoint = 1450;
    
     
    
      useEffect(() => {
       const handleWindowResize = () => setWidth(window.innerWidth);
       window.addEventListener("resize", handleWindowResize);
    
        
       return () => window.removeEventListener("resize", handleWindowResize);
      },[]);
    
      return (
        
    {width > breakPoint? (
    I show on 1451px or higher
    ) : (
    I show on 1450px or lower
    )}
    ); }
    
    

提交回复
热议问题