Skip to content

Instantly share code, notes, and snippets.

@cspilhere
Created October 13, 2020 15:28
Show Gist options
  • Select an option

  • Save cspilhere/b0fd3c172ffcd0c588b8bc8945b2933b to your computer and use it in GitHub Desktop.

Select an option

Save cspilhere/b0fd3c172ffcd0c588b8bc8945b2933b to your computer and use it in GitHub Desktop.

Revisions

  1. cspilhere revised this gist Oct 13, 2020. 1 changed file with 66 additions and 1 deletion.
    67 changes: 66 additions & 1 deletion useViewport.js
    Original file line number Diff line number Diff line change
    @@ -1 +1,66 @@
    ‎‎
    import React, {
    createContext,
    useEffect,
    useState,
    useContext
    } from 'react';

    const Context = createContext({});

    export const ViewportProvider = ({ children }) => {
    const [width, setWidth] = useState(window.innerWidth);
    const [height, setHeight] = useState(window.innerHeight);
    const handler = () => {
    setWidth(window.innerWidth);
    setHeight(window.innerHeight);
    };
    useEffect(() => {
    window.addEventListener('resize', handler);
    return () => window.removeEventListener('resize', handler);
    }, []);

    return (
    <Context.Provider
    value={{
    width,
    height
    }}>
    {children}
    </Context.Provider>
    );
    };

    const useViewport = () => {
    const { width, height } = useContext(Context);
    const breakpoints = {
    xs: 415,
    sm: 768,
    md: 1024,
    lg: 1280,
    xl: 2048
    };
    return {

    width,
    height,

    isXs: width > breakpoints.xs && width < breakpoints.sm,
    isSm: width > breakpoints.sm && width < breakpoints.md,
    isMd: width > breakpoints.md && width < breakpoints.lg,
    isLg: width > breakpoints.lg && width < breakpoints.xl,
    isXl: width > breakpoints.xl,

    isAboveXs: width > breakpoints.xs,
    isAboveSm: width > breakpoints.sm,
    isAboveMd: width > breakpoints.md,
    isAboveLg: width > breakpoints.lg,

    isBelowXs: width < breakpoints.xs,
    isBelowSm: width < breakpoints.sm,
    isBelowMd: width < breakpoints.md,
    isBelowLg: width < breakpoints.lg

    };
    };

    export default useViewport;
  2. cspilhere created this gist Oct 13, 2020.
    1 change: 1 addition & 0 deletions useViewport.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    ‎‎