Last active
April 1, 2023 00:01
-
-
Save RaddishIoW/08c74444f5872495fe53a16e779a1fe5 to your computer and use it in GitHub Desktop.
A React Hooks-based component using Luxon to format a date to a relative string representation, updating that string once a minute.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import PropTypes from 'prop-types' | |
import { DateTime } from 'luxon' | |
const RelativeTime = (props) => { | |
const dt = DateTime.fromJSDate(props.time) | |
const [relTime, setRelTime] = useState(dt.toRelative()) | |
const [intervalID, setIntervalID] = useState() | |
useEffect(() => { | |
let mounted = true | |
setIntervalID(setInterval(() => { | |
if (mounted) { | |
setRelTime(dt.toRelative()) | |
} | |
}, 60000) | |
) | |
return function cleanup () { | |
mounted = false | |
clearInterval(intervalID) | |
} | |
}, []) | |
return ( | |
<> | |
{relTime} | |
</> | |
) | |
} | |
RelativeTime.propTypes = { | |
time: PropTypes.instanceOf(Date) | |
} | |
export default RelativeTime |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment