From 2c4e7f33620af18d58d7d23ecba3afc5780144bf Mon Sep 17 00:00:00 2001 From: Alex Gabites Date: Mon, 31 Jul 2023 17:25:12 +1200 Subject: [PATCH] Recalculate width/height on window resize --- package.json | 3 ++- src/components/TextTransition.tsx | 25 ++++++++++++++++++++----- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index b471bd8..d4eb751 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,8 @@ "webpack-dev-server": "^4.9.2" }, "dependencies": { - "@react-spring/web": "^9.7.2" + "@react-spring/web": "^9.7.2", + "use-debounce": "^9.0.4" }, "peerDependencies": { "react": ">=18.0.0" diff --git a/src/components/TextTransition.tsx b/src/components/TextTransition.tsx index 478d674..ef27a8f 100644 --- a/src/components/TextTransition.tsx +++ b/src/components/TextTransition.tsx @@ -1,13 +1,15 @@ -import React, { useState, useRef, useEffect } from 'react'; +import React, { useCallback, useEffect, useRef, useState } from 'react'; import type { CSSProperties, PropsWithChildren } from 'react'; -import { useSpring, useTransition, animated, config, SpringConfig } from '@react-spring/web'; +import { SpringConfig, animated, config, useSpring, useTransition } from '@react-spring/web'; +import { useDebouncedCallback } from 'use-debounce'; export interface TextTransitionProps { className?: string; delay?: number; direction?: 'up' | 'down'; inline?: boolean; + resizeDebounceMs?: number; springConfig?: SpringConfig; style?: CSSProperties; translateValue?: string; @@ -17,6 +19,7 @@ function TextTransition(props: PropsWithChildren) { const { direction = 'up', inline = false, + resizeDebounceMs = 50, springConfig = config.default, delay = 0, className, @@ -46,8 +49,7 @@ function TextTransition(props: PropsWithChildren) { const currentRef = useRef(null); const heightRef = useRef('auto'); - useEffect(() => { - initialRun.current = false; + const onResize = useCallback(() => { const element = currentRef.current; // If element doesn't exist, then do nothing @@ -57,7 +59,20 @@ function TextTransition(props: PropsWithChildren) { setWidth(width); heightRef.current = height; - }, [children, setWidth, currentRef]); + }, [setWidth, currentRef]); + + useEffect(() => { + initialRun.current = false; + onResize(); + }, [children, onResize]); + + const resizeHandler = useDebouncedCallback(onResize, resizeDebounceMs); + + useEffect(() => { + window.addEventListener('resize', resizeHandler); + + return () => window.removeEventListener('resize', resizeHandler); + }, [resizeHandler]); const widthTransition = useSpring({ to: { width },