Do all the chart sizing work in same batch

This commit is contained in:
Marshall Polaris 2022-09-30 16:53:28 -07:00
parent d4ae1658c2
commit ed635a0487
2 changed files with 17 additions and 25 deletions

View File

@ -1,4 +1,4 @@
import React, { useRef } from 'react'
import React, { useEffect, useRef, useState } from 'react'
import { tradingAllowed } from 'web/lib/firebase/contracts'
import { Col } from '../layout/col'
@ -24,8 +24,6 @@ import {
BinaryContract,
} from 'common/contract'
import { ContractDetails } from './contract-details'
import { useElementWidth } from 'web/hooks/use-element-width'
import { useIsMobile } from 'web/hooks/use-is-mobile'
const OverviewQuestion = (props: { text: string }) => (
<Linkify className="text-lg text-indigo-700 sm:text-2xl" text={props.text} />
@ -53,16 +51,27 @@ const SizedContractChart = (props: {
}) => {
const { contract, bets, fullHeight, mobileHeight } = props
const containerRef = useRef<HTMLDivElement>(null)
const isMobile = useIsMobile(800)
const width = useElementWidth(containerRef)
const [chartWidth, setChartWidth] = useState<number>()
const [chartHeight, setChartHeight] = useState<number>()
useEffect(() => {
const handleResize = () => {
setChartHeight(window.innerWidth < 800 ? mobileHeight : fullHeight)
setChartWidth(containerRef.current?.clientWidth)
}
handleResize()
window.addEventListener('resize', handleResize)
return () => {
window.removeEventListener('resize', handleResize)
}
}, [fullHeight, mobileHeight])
return (
<div ref={containerRef}>
{width != null && (
{chartWidth != null && chartHeight != null && (
<ContractChart
contract={contract}
bets={bets}
width={width}
height={isMobile ? mobileHeight : fullHeight}
width={chartWidth}
height={chartHeight}
/>
)}
</div>

View File

@ -1,17 +0,0 @@
import { RefObject, useState, useEffect } from 'react'
// todo: consider consolidation with use-measure-size
export const useElementWidth = <T extends Element>(ref: RefObject<T>) => {
const [width, setWidth] = useState<number>()
useEffect(() => {
const handleResize = () => {
setWidth(ref.current?.clientWidth)
}
handleResize()
window.addEventListener('resize', handleResize)
return () => {
window.removeEventListener('resize', handleResize)
}
}, [ref])
return width
}