Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to rerender a page using UseEffect hook on window.innerWidth in react

I want to make some changes depending on the screen size

useEffect(() => {
        console.log("am called");

     if (window.innerWidth < 800) {
        document.getElementsByTagName("body")[0].style.display = "none";
     }
     if (window.innerWidth > 800) {
            document.getElementsByTagName("body")[0].style.display = "block";
        }

        
    }, [window.innerWidth]);

what is the problem with this code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to observe window size changing and put this value to state.

    const [width, setWidth] = useState(0)
    useEffect(() => {
        const onResize = () => setWidth(window.innerWidth)
        window.addEventListener('resize', onResize);
        return () => {
            window.removeEventListener("resize", onResize)
        }
    }, [setWidth])

    //and then
    useEffect(() => {
        console.log("am called");

        if (width< 800) {
            document.getElementsByTagName("body")[0].style.display = "none";
        } else {
            document.getElementsByTagName("body")[0].style.display = "block";
        }


    }, [width]);

better solution

export default function useMatchMedia(condition) {
    const [isMatching, setIsMatching] = useState(false);

    useEffect(
        function updateMatchMedia() {
            if (!condition) return setIsMatching(true);

            const updateIsMatching = (event) => setIsMatching(event.matches);

            const matcher = window.matchMedia(condition);

            setIsMatching(matcher.matches);

            matcher.addEventListener('change', updateIsMatching);

            return () => {
                matcher.removeEventListener('change', updateIsMatching);
            };
        },
        [condition]
    );

    return [isMatching];
}

then you can use it

   isTablet = useMatchMedia(`(max-width: 800px)`);
   useEffect(() => {
     if(isTablet){
     } else {
     }
   }, [isTablet])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading