Skip to content

Commit

Permalink
automatically provide localised Date for SSR in RelativeTime (#4305)
Browse files Browse the repository at this point in the history
* automatically provide localised Date for SSR in RelativeTime

* changeset

* fix and add tests

* format

* fix types
  • Loading branch information
keithamus authored Mar 19, 2024
1 parent d16f4fc commit 37c4770
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/honest-feet-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/react': patch
---

Render SSR date for RelativeTime
15 changes: 13 additions & 2 deletions packages/react/src/RelativeTime/RelativeTime.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
import React from 'react'
import {RelativeTimeElement} from '@github/relative-time-element'
import type {ComponentProps} from '../utils/types'
import {createComponent} from '../utils/custom-element'

const RelativeTime = createComponent(RelativeTimeElement, 'relative-time')
const RelativeTimeComponent = createComponent(RelativeTimeElement, 'relative-time')

export type RelativeTimeProps = ComponentProps<typeof RelativeTime>
const localeOptions: Intl.DateTimeFormatOptions = {month: 'short', day: 'numeric', year: 'numeric'}
function RelativeTime({date, datetime, ...props}: RelativeTimeProps) {
if (datetime) date = new Date(datetime)
return (
<RelativeTimeComponent {...props} date={date}>
{date?.toLocaleDateString('en', localeOptions) || ''}
</RelativeTimeComponent>
)
}

export type RelativeTimeProps = ComponentProps<typeof RelativeTimeComponent>
export default RelativeTime
10 changes: 10 additions & 0 deletions packages/react/src/__tests__/RelativeTime.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,14 @@ describe('RelativeTime', () => {
it('renders a <relative-time>', () => {
expect(render(<RelativeTime />).type).toEqual('relative-time')
})

it('renders a date inside', () => {
const date = new Date('2024-03-07T12:22:48.123Z')
expect(render(<RelativeTime date={date} />).children).toEqual(['Mar 7, 2024'])
})

it('renders a datetime inside', () => {
const date = new Date('2024-03-07T12:22:48.123Z')
expect(render(<RelativeTime datetime={date.toJSON()} />).children).toEqual(['Mar 7, 2024'])
})
})

0 comments on commit 37c4770

Please sign in to comment.