summaryrefslogtreecommitdiff
path: root/src/hooks/useRemainingViewPortHeight.js
blob: e917831403434a5ef58f7615df958e53d38ee592 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { useState, useRef, useLayoutEffect, useCallback } from 'react';
/**
 * cosnt [ref, remainingHeight] = useRemainingViewPortHeight();
 *
 * return a reference, and the remaining height of the referenced dom node
 * to the bottom of the view port
 *
 */
export default function useRemainingViewPortHeight() {
  const refRulesContainer = useRef(null);
  const [containerHeight, setContainerHeight] = useState(200);
  function _updateContainerHeight() {
    const { top } = refRulesContainer.current.getBoundingClientRect();
    setContainerHeight(window.innerHeight - top);
  }
  const updateContainerHeight = useCallback(_updateContainerHeight, []);

  useLayoutEffect(() => {
    updateContainerHeight();
    window.addEventListener('resize', updateContainerHeight);
    return () => {
      window.removeEventListener('resize', updateContainerHeight);
    };
  }, []);

  return [refRulesContainer, containerHeight];
}