Last active
May 8, 2020 07:11
-
-
Save drkdelaney/bc5c0adf5cece53863f6f094cb240251 to your computer and use it in GitHub Desktop.
Add the window size as a prop to your React component. For class and function components with hooks.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from 'react'; | |
export enum WINDOW_SIZE { | |
XSMALL = 375, | |
SMALL = 768, | |
MEDIUM = 1024, | |
LARGE = 1200, | |
XLARGE = 1440, | |
} | |
export interface WindowSizeProps { | |
size: WINDOW_SIZE; | |
width: number; | |
height: number; | |
} | |
function getSize() { | |
if (window.innerWidth >= WINDOW_SIZE.XLARGE) { | |
return WINDOW_SIZE.XLARGE; | |
} else if (window.innerWidth >= WINDOW_SIZE.LARGE) { | |
return WINDOW_SIZE.LARGE; | |
} else if (window.innerWidth >= WINDOW_SIZE.MEDIUM) { | |
return WINDOW_SIZE.MEDIUM; | |
} else if (window.innerWidth >= WINDOW_SIZE.SMALL) { | |
return WINDOW_SIZE.SMALL; | |
} else { | |
return WINDOW_SIZE.XSMALL; | |
} | |
} | |
const useWindowSize = (): WindowSizeProps => { | |
const [size, setSize] = useState(getSize()); | |
const [width, setWidth] = useState(window.innerWidth); | |
const [height, setHeight] = useState(window.innerHeight); | |
useEffect(() => { | |
function handleResize() { | |
setSize(getSize()); | |
setWidth(window.innerWidth); | |
setHeight(window.innerHeight); | |
} | |
window.addEventListener('resize', handleResize); | |
return () => window.removeEventListener('resize', handleResize); | |
}, []); | |
return { size, width, height }; | |
}; | |
const withWindowSize = <P extends WindowSizeProps>(Component: React.ComponentType<P>) => | |
class WithWindowSize extends React.Component<Omit<P, keyof WindowSizeProps>> { | |
public state = { | |
size: getSize(), | |
width: window.innerWidth, | |
height: window.innerHeight, | |
} | |
public handleResize = () => { | |
this.setState({ | |
size: getSize(), | |
width: window.innerWidth, | |
height: window.innerHeight, | |
}); | |
} | |
public componentDidMount() { | |
window.addEventListener('resize', this.handleResize); | |
} | |
public componentWillUnmount() { | |
window.removeEventListener('resize', this.handleResize); | |
} | |
public render() { | |
return <Component {...this.state } { ...this.props as P} />; | |
} | |
}; | |
export { withWindowSize, useWindowSize }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment