Skip to content

Instantly share code, notes, and snippets.

@srph
Created June 2, 2019 09:55
Show Gist options
  • Save srph/64dda5e248f92531b3c850c9c16da805 to your computer and use it in GitHub Desktop.
Save srph/64dda5e248f92531b3c850c9c16da805 to your computer and use it in GitHub Desktop.
React: Get the current date periodically

Usage

<PeriodicNow interval={1000}>
  {(now: Date) => (
    //
  )}
</PeriodicNow>
import * as React from 'react'
interface Props {
interval: number
children: (now: Date) => React.ReactNode
}
interface State {
now: Date
}
class PeriodicNow extends React.Component<Props, State> {
state = {
now: new Date()
}
interval: number
componentDidMount() {
this.interval = window.setInterval(() => {
this.setState({
now: new Date()
})
}, this.props.interval)
}
componentWillUnmount() {
window.clearInterval(this.interval)
}
render() {
return this.props.children(this.state.now)
}
}
export default PeriodicNow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment