github.com/filecoin-project/bacalhau@v0.3.23-0.20230228154132-45c989550ace/dashboard/frontend/src/components/widgets/HeightDiv.tsx (about)

     1  import React, { FC, useState, useRef, useCallback, useEffect } from 'react'
     2  import { SxProps } from '@mui/system'
     3  import Box from '@mui/material/Box'
     4  
     5  const HeightDiv: FC<{
     6    percent?: number,
     7    sx?: SxProps,
     8  }> = ({
     9    percent = 100,
    10    sx = {},
    11    children,
    12  }) => {
    13  
    14    const mounted = useRef(true)
    15    const [ width, setWidth ] = useState(0)
    16    const ref = useRef<HTMLDivElement>()
    17  
    18    const calculateWidth = () => {
    19      if(!mounted.current || !ref.current) return
    20      setWidth(ref.current.offsetWidth * percent)
    21    }
    22  
    23    useEffect(() => {
    24      const handleResize = () => calculateWidth()
    25      handleResize()
    26      window.addEventListener('resize', handleResize)
    27      return () => window.removeEventListener('resize', handleResize)
    28    }, [])
    29  
    30    useEffect(() => {
    31      mounted.current = true
    32      return () => {
    33        mounted.current = false
    34      }
    35    }, [])
    36  
    37    return (
    38      <Box
    39        component="div"
    40        sx={{
    41          width: '100%',
    42          height: `${width}px`,
    43          ...sx
    44        }}
    45        ref={ ref }
    46      >
    47        { children }
    48      </Box>
    49    )
    50  }
    51  
    52  export default HeightDiv