refactor: extract height monitor hook

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
Tilman Vatteroth 2023-05-31 20:36:31 +02:00
parent 21b2fb042c
commit 71e5d00f55
3 changed files with 41 additions and 14 deletions

View file

@ -0,0 +1,34 @@
/*
* SPDX-FileCopyrightText: 2023 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import useResizeObserver from '@react-hook/resize-observer'
import type { RefObject } from 'react'
import { useEffect, useState } from 'react'
/**
* Monitors the height of the referenced {@link HTMLElement} and executes the callback on change.
*
* @param elementRef The reference that contains the element to watch
* @param onHeightChange The callback that should be executed if the height changes
*/
export const useOnHeightChange = (
elementRef: RefObject<HTMLElement>,
onHeightChange: undefined | ((value: number) => void)
): void => {
const [rendererSize, setRendererSize] = useState<number>(0)
useResizeObserver(elementRef, (entry) => {
setRendererSize(entry.contentRect.height)
})
useEffect(() => {
const value = elementRef.current?.clientHeight
if (value === undefined) {
return
}
setRendererSize(value)
}, [elementRef])
useEffect(() => {
onHeightChange?.(rendererSize + 1)
}, [rendererSize, onHeightChange])
}