<PeriodicNow interval={1000}>
{(now: Date) => (
//
)}
</PeriodicNow>
Created
June 2, 2019 09:55
-
-
Save srph/64dda5e248f92531b3c850c9c16da805 to your computer and use it in GitHub Desktop.
React: Get the current date periodically
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 * 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