Skip to content

Commit

Permalink
add useAvailableHeight hook
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexBHdez committed Jan 20, 2025
1 parent 39b8586 commit b17e2a2
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/playground/Collections/Table/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
} from "@tanstack/react-table"
import { useVirtualizer } from "@tanstack/react-virtual"
import React, { useCallback, useMemo, useRef, useState } from "react"
import useAvailableHeight from "./lib/useAvailableHeight"

export type ColumnMeta<TData, TValue> = ReactTableColumnMeta<TData, TValue> & {
options?: Array<{ value: string | number; label: string }>
Expand All @@ -36,6 +37,7 @@ export const Table = <TData extends object>({
const [tableData, setTableData] = useState<TData[]>(data)
const [globalFilter, setGlobalFilter] = useState("")
const tableContainerRef = useRef<HTMLDivElement>(null)
const availableHeight = useAvailableHeight(tableContainerRef)

const updateData = useCallback(
(rowIndex: number, columnId: string, value: unknown) => {
Expand Down Expand Up @@ -164,7 +166,11 @@ export const Table = <TData extends object>({
</div>
))}
</div>
<div ref={tableContainerRef} className="relative h-96 overflow-auto">
<div
ref={tableContainerRef}
className="relative h-96 overflow-auto"
style={{ height: `${availableHeight}px` }}
>
<table className="w-full border-spacing-0 rounded-xl">
<tbody className="relative" style={{ height: `${totalSize}px` }}>
{virtualRows.map((virtualRow) => {
Expand Down
31 changes: 31 additions & 0 deletions src/playground/Collections/Table/lib/useAvailableHeight.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { RefObject, useEffect, useState } from "react"

function useAvailableHeight(elementRef: RefObject<HTMLElement>, offset = 0) {
const [availableHeight, setAvailableHeight] = useState(0)

useEffect(() => {
if (!elementRef.current) return

const updateHeight = () => {
const element = elementRef.current

if (!element) return

const rect = element.getBoundingClientRect()
const availableHeight = window.innerHeight - rect.top - offset

setAvailableHeight(availableHeight)
}

updateHeight()
window.addEventListener("resize", updateHeight)

return () => {
window.removeEventListener("resize", updateHeight)
}
}, [elementRef, offset])

return availableHeight
}

export default useAvailableHeight

0 comments on commit b17e2a2

Please sign in to comment.