gt-next@6.15.0
Panoramica
Un nuovo componente <RelativeTime> è ora disponibile in tutti i pacchetti React di GT. Esegue il rendering di stringhe localizzate di tempo relativo come "2 ore fa" o "tra 3 giorni" utilizzando l'API Intl.RelativeTimeFormat integrata del browser.
| Pacchetto | Versione | Export |
|---|---|---|
gt-next | 6.15.0 | <RelativeTime> (client + server) |
gt-react | 10.16.0 | <RelativeTime> (client) |
gt-tanstack-start | 0.3.0 | <RelativeTime> (client) |
generaltranslation | 8.2.0 | formatRelativeTimeFromDate() (core) |
gt (CLI) | 2.14.0 | rilevamento del componente RelativeTime |
Utilizzo
Selezione automatica dell'unità da una Date
Passa una Date e il componente selezionerà automaticamente l'unità più adatta (secondi, minuti, ore, giorni, settimane, mesi o anni).
import { RelativeTime } from 'gt-next';
export default function PostTimestamp({ post }) {
return <RelativeTime>{post.createdAt}</RelativeTime>;
// "2 ore fa", "3 giorni fa", "tra 5 minuti", ecc.
}Valore e unità espliciti
Specifica un valore e un'unità esatti, in linea con Intl.RelativeTimeFormat.
import { RelativeTime } from 'gt-next';
export default function Reminder() {
return (
<p>
Your trial ends <RelativeTime value={3} unit="day" />.
</p>
);
// "Il tuo periodo di prova termina tra 3 giorni."
}Nel contenuto tradotto
Racchiudi <RelativeTime> in un componente <T> per includerlo nelle frasi tradotte.
import { T, RelativeTime } from 'gt-next';
export default function Comment({ comment }) {
return (
<T id="commentPosted">
Posted <RelativeTime>{comment.createdAt}</RelativeTime>
</T>
);
}Funzione principale
Per i contesti non basati su componenti, usa la funzione autonoma:
import { formatRelativeTimeFromDate } from 'generaltranslation';
const label = formatRelativeTimeFromDate(someDate, {
locales: ['en-US'],
baseDate: new Date(),
});
// "2 ore fa"Affidabilità dell'idratazione
<RelativeTime> calcola il tempo relativo localmente, il che può causare errori di idratazione nelle app con rendering eseguito sul server. Fissa baseDate e locales per mantenere server e client sincronizzati:
const now = new Date();
<RelativeTime baseDate={now} locales={['en-US']}>
{post.createdAt}
</RelativeTime>