Skip to content

Instantly share code, notes, and snippets.

@GGAlanSmithee
Last active July 13, 2020 03:17
Show Gist options
  • Save GGAlanSmithee/a5883c098847bebcd5092f3faa30b536 to your computer and use it in GitHub Desktop.
Save GGAlanSmithee/a5883c098847bebcd5092f3faa30b536 to your computer and use it in GitHub Desktop.
react-router DelayedRedirect
import * as React from 'react'
import { Redirect, RedirectProps } from 'react-router'
interface DelayedProps {
delay: number
}
interface DelayedState {
timeToRedirect: boolean
}
class DelayedRedirect extends React.Component<
RedirectProps & DelayedProps,
DelayedState
> {
timeout: any = null
state: DelayedState = {
timeToRedirect: false,
}
componentDidMount() {
this.timeout = setTimeout(() => {
this.setState({
timeToRedirect: true,
})
}, this.props.delay)
}
componentWillUnmount() {
clearTimeout(this.timeout)
}
render() {
const { delay, ...props } = this.props
const { timeToRedirect } = this.state
if (timeToRedirect) {
return <Redirect {...props} />
}
return null
}
}
export default DelayedRedirect
import * as React from 'react'
import { DelayedRedirect } from './delayed-redirect'
const Test = () => (
<div>
Redirect to "/" in fem seconds
<DelayedRedirect to={'/'} delay={5000} />
</div>
)
export default Test
@GGAlanSmithee
Copy link
Author

See remix-run/react-router#6422 for context

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment