SHARE
TWEET

Untitled

a guest Apr 27th, 2020 70 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. // ViewportContext.tsx
  3. //
  4.  
  5. import * as React from 'react';
  6. import { isSSR } from '@lib/ssr';
  7.  
  8. export const ViewportContext = React.createContext({} as ViewportProps);
  9.  
  10. export const ViewportProvider: React.FC = ({ children }) => {
  11.     const [width, setWidth] = React.useState(isSSR ? 0 : window.innerWidth);
  12.     const [height, setHeight] = React.useState(isSSR ? 0 : window.innerHeight);
  13.  
  14.     const handleResize = () => {
  15.         setWidth(window.innerWidth);
  16.         setHeight(window.innerHeight);
  17.     };
  18.  
  19.     React.useEffect(() => {
  20.         window.addEventListener('resize', handleResize);
  21.  
  22.         return () => {
  23.             window.removeEventListener('resize', handleResize);
  24.         };
  25.     }, []);
  26.     return (
  27.         <ViewportContext.Provider value={{ width, height }}>
  28.             {children}
  29.         </ViewportContext.Provider>
  30.     );
  31. };
  32.  
  33. interface ViewportProps {
  34.     width: number;
  35.     height: number;
  36. }
  37.  
  38.  
  39. //
  40. //useViewport.tsx
  41. //
  42. import * as React from 'react';
  43. import { ViewportContext } from '@context';
  44.  
  45. export const useViewport = () => {
  46.     const { width, height } = React.useContext(ViewportContext);
  47.     return { width, height };
  48. };
  49.  
  50.  
  51. //
  52. // ResponsiveLayout.tsx
  53. // This is my component that is handling the responsive rendering
  54. //
  55. import * as React from 'react';
  56. import { useViewport } from '@hooks';
  57. import { mediaQuerySizes, AvailableBreakpoint } from '@tokens';
  58.  
  59.  
  60. export const ResponsiveLayout: React.FC<ResponsiveLayoutProps> = ({
  61.     breakpoint,
  62.     mobileView,
  63.     desktopView,
  64. }) => {
  65.     const { width } = useViewport();
  66.     const selectedBreakpoint = mediaQuerySizes[breakpoint];
  67.  
  68.     return width < selectedBreakpoint ? mobileView() : desktopView();
  69. };
  70.  
  71. interface ResponsiveLayoutProps {
  72.     breakpoint: AvailableBreakpoint;
  73.     mobileView: () => React.ReactElement | null;
  74.     desktopView: () => React.ReactElement | null;
  75. }
  76.  
  77.  
  78. //
  79. // __tokens__/breakpoints.ts
  80. //
  81. // Including this just for reference to show where my breakpoint values are coming from
  82. //
  83. export const mediaQuerySizes: AvailableBreakpoints = {
  84.     xs: 414,
  85.     s: 768,
  86.     m: 960,
  87.     l: 1040,
  88.     xl: 1440,
  89.     xxl: 1640,
  90. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top