Search code examples
javascriptreactjscomponentsscreenswap

How to switch from one screen to another after a certain time in ReactJS?


I'm new to ReactJS and want to implement the following logic: I have an intro screen in my app and after a few seconds I require to swap the intro screen with the home page.

How can I do this?

I have both the intro screen and home page in two separate components and I'm using React Router.

I've been thinking of using a SetTimeOut to change my components, but I don't know how to use it between components.

Here is my App.js code:

import React, {Component} from 'react';
import './App.css';
import {Route, Switch} from 'react-router-dom';
import Intro from './components/Intro';
import Home from './components/Home';
import Work from './components/Work';
import About from './components/About';
import Carrers from './components/Carrers';
import Contact from './components/Contact';

class App extends Component {
 constructor(){
   super()
 }

 render() {
 return (

   <React.Fragment>
     <Switch>
     <Intro path= "/" exact component={Intro}/>
     <Route path= "/home" exact component={Home} />
     <Route path= "/about" exact component={About} />
     <Route path= "/work" exact component={Work} />
     <Route path= "/carrers" exact component={Carrers} />
     <Route path= "/contact" exact component={Contact} />
     </Switch>
   </React.Fragment>
 );
 }
}


export default App;

Could you please advise me on the right approach?


Solution

  • Your intro component can be like this

    class Intro extends React.Component {
    
    
    componentDidMount() {
        setTimeout(() => {
          this.props.history.push('/home')
        }, 5000) // render for 5 seconds and then push to home 
      }
      render() {
        return <h1>render for 5 seconds and then push to home</h1>
      }
    }