addons/isl/src/Delayed.tsxblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318import type {ReactNode} from 'react';
b69ab319
b69ab3110import {useEffect, useState} from 'react';
b69ab3111
b69ab3112/**
b69ab3113 * Hide children until the given timestamp.
b69ab3114 */
b69ab3115export function Delayed({
b69ab3116 children,
b69ab3117 hideUntil,
b69ab3118}: {
b69ab3119 children: ReactNode;
b69ab3120 hideUntil: Date;
b69ab3121}): JSX.Element {
b69ab3122 const [visible, setVisible] = useState(false);
b69ab3123 useEffect(() => {
b69ab3124 const delay = hideUntil.getTime() - Date.now();
b69ab3125 if (delay > 0) {
b69ab3126 setVisible(false);
b69ab3127 const timer = setTimeout(() => {
b69ab3128 setVisible(true);
b69ab3129 }, delay);
b69ab3130 return () => clearTimeout(timer);
b69ab3131 } else {
b69ab3132 setVisible(true);
b69ab3133 }
b69ab3134 }, [hideUntil, setVisible]);
b69ab3135
b69ab3136 // Cast to JSX.Element to make testing-library happy.
b69ab3137 return (visible ? children : null) as JSX.Element;
b69ab3138}