Skip to content

Commit 449a627

Browse files
feat: add default time for time component
1 parent 24efd92 commit 449a627

File tree

1 file changed

+39
-4
lines changed
  • packages/sdk-components-react/src

1 file changed

+39
-4
lines changed

packages/sdk-components-react/src/time.tsx

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
import { forwardRef, type ComponentProps, type ElementRef } from "react";
1+
import {
2+
forwardRef,
3+
useEffect,
4+
useState,
5+
type ComponentProps,
6+
type ElementRef,
7+
} from "react";
28

39
const languages = [
410
"af",
@@ -281,7 +287,15 @@ type Country = (typeof countries)[number];
281287
type DateStyle = Intl.DateTimeFormatOptions["dateStyle"] | "none";
282288
type TimeStyle = Intl.DateTimeFormatOptions["timeStyle"] | "none";
283289

284-
const INITIAL_DATE_STRING = "dateTime attribute is not set";
290+
const createInitialDate = () => {
291+
const date = new Date();
292+
date.setSeconds(0);
293+
date.setMilliseconds(0);
294+
return date;
295+
};
296+
297+
const INITIAL_DATE_STRING =
298+
typeof window === "undefined" ? createInitialDate() : null;
285299
const INVALID_DATE_STRING = "";
286300

287301
const DEFAULT_LANGUAGE = "en";
@@ -365,6 +379,9 @@ export const Time = forwardRef<ElementRef<"time">, TimeProps>(
365379
},
366380
ref
367381
) => {
382+
const [clientSideDate, setClientSideDate] = useState<string | Date | null>(
383+
null
384+
);
368385
const locale = `${languageOrDefault(language)}-${countryOrDefault(
369386
country
370387
)}`;
@@ -374,8 +391,21 @@ export const Time = forwardRef<ElementRef<"time">, TimeProps>(
374391
timeStyle: timeStyleOrUndefined(timeStyle),
375392
};
376393

394+
useEffect(() => {
395+
if (dateTime === INITIAL_DATE_STRING) {
396+
setClientSideDate(new Date());
397+
}
398+
}, [dateTime]);
399+
400+
const dateToUse =
401+
typeof window !== "undefined" &&
402+
clientSideDate !== null &&
403+
dateTime === INITIAL_DATE_STRING
404+
? clientSideDate
405+
: dateTime;
406+
377407
const datetimeString =
378-
dateTime === null ? INVALID_DATE_STRING : dateTime.toString();
408+
dateToUse === null ? INVALID_DATE_STRING : dateToUse.toString();
379409

380410
const date = parseDate(datetimeString);
381411
let formattedDate = datetimeString;
@@ -389,7 +419,12 @@ export const Time = forwardRef<ElementRef<"time">, TimeProps>(
389419
}
390420

391421
return (
392-
<time ref={ref} dateTime={datetimeString} {...props}>
422+
<time
423+
ref={ref}
424+
dateTime={datetimeString}
425+
{...props}
426+
suppressHydrationWarning
427+
>
393428
{formattedDate}
394429
</time>
395430
);

0 commit comments

Comments
 (0)