From 1a7af1be2a989241e59e380ef45e8545b323a5fa Mon Sep 17 00:00:00 2001 From: 0x1eef <0x1eef@protonmail.com> Date: Mon, 4 Dec 2023 01:36:58 -0300 Subject: [PATCH] useRef / useMemo in Stream.tsx --- src/js/components/Stream.tsx | 62 ++++++++++++++++++++---------------- 1 file changed, 34 insertions(+), 28 deletions(-) diff --git a/src/js/components/Stream.tsx b/src/js/components/Stream.tsx index 2afafb86a..211da4cee 100644 --- a/src/js/components/Stream.tsx +++ b/src/js/components/Stream.tsx @@ -1,4 +1,4 @@ -import React, { useEffect } from "react"; +import React, { useEffect, useMemo, useRef } from "react"; import * as Quran from "lib/Quran"; import { AudioControl } from "components/AudioControl"; import { formatNumber, TFunction } from "lib/i18n"; @@ -26,37 +26,43 @@ export function Stream({ const className = classNames("body", "stream"); const style: React.CSSProperties = endOfStream || isPaused ? { overflowY: "auto" } : { overflowY: "hidden" }; - const ayat = stream.map((ayah: Quran.Ayah) => { - return ( -
  • - - {(isPaused || endOfStream) && ( - turnOffSound()} - /> - )} - - {t(locale, "surah")} {formatNumber(surah.id, locale)} - {t(locale, "comma")} {t(locale, "ayah")}{" "} - {formatNumber(ayah.id, locale)} + const ul = useRef(); + const ayat = useMemo(() => { + return stream.map((ayah: Quran.Ayah) => { + return ( +
  • + + {(isPaused || endOfStream) && ( + turnOffSound()} + /> + )} + + {t(locale, "surah")} {formatNumber(surah.id, locale)} + {t(locale, "comma")} {t(locale, "ayah")}{" "} + {formatNumber(ayah.id, locale)} + - -

    {ayah.text}

    -
  • - ); - }); - - useEffect(() => { - const ul: HTMLElement = document.querySelector("ul.stream")!; - const top = ul.offsetHeight + ul.scrollTop; - ul.scrollBy({ behavior: "smooth", top }); +

    {ayah.text}

    + + ); + }); }, [stream.length]); + useEffect(() => { + const el = ul.current; + if (el) { + const top = el.scrollHeight + el.scrollTop; + el.scrollTo({ behavior: "smooth", top }); + el.scrollIntoView({ behavior: "smooth" }); + } + }, [ul.current, stream.length]); + return ( -