Last active
September 25, 2020 10:15
-
-
Save loilo/e62e26b1c1f1e1a23c30b43463ae0b77 to your computer and use it in GitHub Desktop.
useTerminalSize() React Hook
This file contains hidden or 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 { useEffect, useState } from 'react' | |
| /** | |
| * React hook which provides the size of the terminal, based on https://usehooks.com/useWindowSize/ | |
| * Great for usage with Ink (https://npmjs.com/package/ink) | |
| */ | |
| export function useTerminalSize() { | |
| const [terminalSize, setTerminalSize] = useState([ | |
| process.stdout.columns, | |
| process.stdout.rows | |
| ]) | |
| useEffect(() => { | |
| // Handler to call on window resize | |
| function handleResize() { | |
| // Set window width/height to state | |
| setTerminalSize([ | |
| process.stdout.columns, | |
| process.stdout.rows | |
| ]) | |
| } | |
| // Add event listener | |
| process.stdout.on('resize', handleResize) | |
| // Remove event listener on cleanup | |
| return () => { | |
| process.stdout.off('resize', handleResize) | |
| } | |
| }, []) // Empty array ensures that effect is only run on mount | |
| return terminalSize | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment