From 173d2304eaab4048dd56e6e9c4b86a698dce4122 Mon Sep 17 00:00:00 2001 From: Marshall Polaris Date: Sun, 2 Oct 2022 15:20:33 -0700 Subject: [PATCH] Extract SizedContainer helper component --- web/components/contract/contract-overview.tsx | 35 +++++++------------ web/components/sized-container.tsx | 35 +++++++++++++++++++ 2 files changed, 47 insertions(+), 23 deletions(-) create mode 100644 web/components/sized-container.tsx diff --git a/web/components/contract/contract-overview.tsx b/web/components/contract/contract-overview.tsx index 2a6d5172..95600a8e 100644 --- a/web/components/contract/contract-overview.tsx +++ b/web/components/contract/contract-overview.tsx @@ -1,5 +1,3 @@ -import React, { useEffect, useRef, useState } from 'react' - import { tradingAllowed } from 'web/lib/firebase/contracts' import { Col } from '../layout/col' import { ContractChart } from 'web/components/charts/contract' @@ -24,6 +22,7 @@ import { BinaryContract, } from 'common/contract' import { ContractDetails } from './contract-details' +import { SizedContainer } from 'web/components/sized-container' const OverviewQuestion = (props: { text: string }) => ( @@ -49,32 +48,18 @@ const SizedContractChart = (props: { fullHeight: number mobileHeight: number }) => { - const { contract, bets, fullHeight, mobileHeight } = props - const containerRef = useRef(null) - const [chartWidth, setChartWidth] = useState() - const [chartHeight, setChartHeight] = useState() - 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]) + const { fullHeight, mobileHeight, contract, bets } = props return ( -
- {chartWidth != null && chartHeight != null && ( + + {(width, height) => ( )} -
+ ) } @@ -114,7 +99,11 @@ const BinaryOverview = (props: { contract: BinaryContract; bets: Bet[] }) => { - + ReactNode +}) => { + const { children, fullHeight, mobileHeight } = props + const threshold = props.mobileThreshold ?? 800 + const containerRef = useRef(null) + const [width, setWidth] = useState() + const [height, setHeight] = useState() + useEffect(() => { + if (containerRef.current) { + const handleResize = () => { + setHeight(window.innerWidth <= threshold ? mobileHeight : fullHeight) + setWidth(containerRef.current?.clientWidth) + } + handleResize() + const resizeObserver = new ResizeObserver(handleResize) + resizeObserver.observe(containerRef.current) + window.addEventListener('resize', handleResize) + return () => { + window.removeEventListener('resize', handleResize) + resizeObserver.disconnect() + } + } + }, [threshold, fullHeight, mobileHeight]) + return ( +
+ {width != null && height != null && children(width, height)} +
+ ) +}