0

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?

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35

2 Answers2

2

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>
  }
}
Kamran Nazir
  • 672
  • 4
  • 11
0

Please refer to this question: Programmatically navigate using react router

Basically, you will get history from props and will use it to push to new route.

const { history } = this.props;
history.push('/new-location')

If you don't see it into your props because it's not the Component from your Route, you will need to use withRouter from 'react-router-dom'.

import { withRouter } from 'react-router-dom';
export default withRouter(Component);
Luis Felipe Perez
  • 339
  • 1
  • 4
  • 18