Back

gt-next@6.15.0

Archie McKenzie avatarArchie McKenzie
gt-nextgt-reactgt-tanstack-startrelative-timecomponents

Overview

A new <RelativeTime> component is now available across all GT React packages. It renders localized relative time strings like "2 hours ago" or "in 3 days" using the browser's built-in Intl.RelativeTimeFormat API.

PackageVersionExport
gt-next6.15.0<RelativeTime> (client + server)
gt-react10.16.0<RelativeTime> (client)
gt-tanstack-start0.3.0<RelativeTime> (client)
generaltranslation8.2.0formatRelativeTimeFromDate() (core)
gt (CLI)2.14.0RelativeTime component detection

Usage

Auto-select unit from a Date

Pass a Date and the component automatically picks the best unit (seconds, minutes, hours, days, weeks, months, or years).

import { RelativeTime } from 'gt-next';

export default function PostTimestamp({ post }) {
  return <RelativeTime>{post.createdAt}</RelativeTime>;
  // "2 hours ago", "3 days ago", "in 5 minutes", etc.
}

Explicit value and unit

Specify an exact value and unit, mirroring Intl.RelativeTimeFormat directly.

import { RelativeTime } from 'gt-next';

export default function Reminder() {
  return (
    <p>
      Your trial ends <RelativeTime value={3} unit="day" />.
    </p>
  );
  // "Your trial ends in 3 days."
}

Inside translated content

Wrap <RelativeTime> in a <T> component to include it in translated sentences.

import { T, RelativeTime } from 'gt-next';

export default function Comment({ comment }) {
  return (
    <T id="commentPosted">
      Posted <RelativeTime>{comment.createdAt}</RelativeTime>
    </T>
  );
}

Core function

For non-component contexts, use the standalone function:

import { formatRelativeTimeFromDate } from 'generaltranslation';

const label = formatRelativeTimeFromDate(someDate, {
  locales: ['en-US'],
  baseDate: new Date(),
});
// "2 hours ago"

Hydration safety

<RelativeTime> computes relative time locally, which can cause hydration mismatches in server-rendered apps. Pin baseDate and locales to keep server and client in sync:

const now = new Date();

<RelativeTime baseDate={now} locales={['en-US']}>
  {post.createdAt}
</RelativeTime>