Skip to content

Instantly share code, notes, and snippets.

@eriksachse
Created September 24, 2021 15:35
Show Gist options
  • Save eriksachse/b596d6be54007f04bc2c8fee792a8fde to your computer and use it in GitHub Desktop.
Save eriksachse/b596d6be54007f04bc2c8fee792a8fde to your computer and use it in GitHub Desktop.

Revisions

  1. eriksachse revised this gist Sep 24, 2021. 1 changed file with 0 additions and 5 deletions.
    5 changes: 0 additions & 5 deletions index.jsx
    Original file line number Diff line number Diff line change
    @@ -1,5 +0,0 @@
    import useWindowDimensions from "./hooks/useWindowDimensions";

    export default function Masonry(props) {
    const { width, height } = useWindowDimensions();
    }
  2. eriksachse revised this gist Sep 24, 2021. 1 changed file with 5 additions and 0 deletions.
    5 changes: 5 additions & 0 deletions index.jsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    import useWindowDimensions from "./hooks/useWindowDimensions";

    export default function Masonry(props) {
    const { width, height } = useWindowDimensions();
    }
  3. eriksachse revised this gist Sep 24, 2021. 1 changed file with 0 additions and 5 deletions.
    5 changes: 0 additions & 5 deletions index.jsx
    Original file line number Diff line number Diff line change
    @@ -1,5 +0,0 @@
    import useWindowDimensions from "./hooks/useWindowDimensions";

    export default function Masonry(props) {
    const { width, height } = useWindowDimensions();
    }
  4. eriksachse created this gist Sep 24, 2021.
    5 changes: 5 additions & 0 deletions index.jsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    import useWindowDimensions from "./hooks/useWindowDimensions";

    export default function Masonry(props) {
    const { width, height } = useWindowDimensions();
    }
    31 changes: 31 additions & 0 deletions useWindowDimensions.jsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    import { useState, useEffect } from "react";

    export default function useWindowDimensions() {
    const hasWindow = typeof window !== "undefined";

    function getWindowDimensions() {
    const width = hasWindow ? window.innerWidth : null;
    const height = hasWindow ? window.innerHeight : null;
    return {
    width,
    height,
    };
    }

    const [windowDimensions, setWindowDimensions] = useState(
    getWindowDimensions()
    );

    useEffect(() => {
    if (hasWindow) {
    function handleResize() {
    setWindowDimensions(getWindowDimensions());
    }

    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
    }
    }, [hasWindow]);

    return windowDimensions;
    }