mirror of
https://github.com/hedgedoc/hedgedoc.git
synced 2025-05-15 23:54:42 -04:00
refactor: extract height monitor hook
Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
parent
21b2fb042c
commit
71e5d00f55
3 changed files with 41 additions and 14 deletions
|
@ -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])
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue