'How to "Redirect to" after 'x' seconds using react-router-dom

I'm beginner in React Js. I would like to redirect to path '/event' after 2 seconds.

This way is not working:

import React from 'react';
import { getFormData } from '../../../helpers/form';
import { eventCreate } from '../../../actions/EventActions';
import { Redirect } from 'react-router-dom';
import { connect } from 'react-redux';

if (event) {
  setTimeout(() => {
    return <Redirect to={'/event'} />;
  }, 2000);
}

But if I change it to:

if (event) {
  return <Redirect to={'/event'} />;
}

It works perfectly. How could I redirect after 2 seconds?



Solution 1:[1]

2022 Update: While updating versions (React 18, React Router DOM 6) I noticed it required a bit of refactor.

import React, { useEffect } from 'react'
import { useNavigate } from 'react-router-dom'

export default function myComponent () {
  const navigate = useNavigate()

  useEffect(() => {
    setTimeout(() => {
      navigate('/event')
    }, 2000)
  }, [])
  return <div>Content</div>
}

2021 Update: After learning more about React, I'd probably recommend using useEffect to mimic the functionality of componentDidMount in a functional component.

import React, { useEffect, useHistory } from 'react'

export default function myComponent () {
  const history = useHistory()

  useEffect(() => {
    setTimeout(() => {
      history.push('/event')
    }, 2000)
  }, [])
  return <div>Content</div>
}

Previous answer: Is your if (event) { inside a component of some sort? I think you could achieve this one of two ways. Either:

componentDidMount() {
  if (event) {
    setTimeout(() => { 
      this.props.history.push('/event');
    }, 2000)
  }
}

Note, to use componentDidMount and this, you'll have to use a class component which I don't see in your example. Or:

class RedirectExample extends Component {
  state = {
    redirect: false
  }

  componentDidMount() {
    this.id = setTimeout(() => this.setState({ redirect: true }), 2000)
  }

  componentWillUnmount() {
    clearTimeout(this.id)
  }

  render() {
    return this.state.redirect
      ? <Redirect to='/event' />
      : <div>Content</div>
  }
}

As requested in a comment, I modified this answer to include a refactor to functional component. Note, the following code is untested but should give you an idea of how you might accomplish it.

import React, { useState } from 'react'
import { Redirect } from 'react-router-dom'

function RedirectExample() {
  const [redirectNow, setRedirectNow] = useState(false)
  if (redirectNow) {
    return <Redirect to='/event' />
  }
  return <div>Content</div>
}

Or possibly (I haven't used useHistory before but from the documentation you might be able to do something like this):

import React from 'react'
import { useHistory } from 'react-router'

function RedirectExample() {
  const history = useHistory()

  // setTimeout may cause an error
  setTimeout(() => {
    history.push('/event')
  }, 2000)
  return <div>Content</div>
}

Solution 2:[2]

In Functional Component you can use useHistory() hook of React like the previous mentioned and it will work but in Class based component you may not be able to do the same thing using Hook. So, if you want to perform the task you can use a little trick by taking an extra state just like this:

 this.state={
    redirect: false
 }


if (event) {
  setTimeout(() => {
    this.setState({
       redirect: true
  }, 2000);
}

 render(){
  
    if(this.state.redirect){
       return <Redirect to='/event'/>
     }
 }

This may helpful for you.

Solution 3:[3]

This worked for me:

import { useState } from "react";
import { Redirect } from "react-router-dom";

function SplashScreen() {
  const [redirectNow, setRedirectNow] = useState(false);
  setTimeout(() => setRedirectNow(true), 2000);
  return redirectNow ? (
    <Redirect to="/game" />
  ) : (
    <div className="SplashScreen">
      <h1>Hello World</h1>
    </div>
  );
}

export default SplashScreen;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 MN86
Solution 3 Flavio Sousa