React conditionally render based on viewport size

后端 未结 4 2113
太阳男子
太阳男子 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:03

    Just to post a recent update here after I had the same issue, but set it up using a functional component and the useEffect / useState React Hooks:

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

提交回复
热议问题