Skip to content
Advertisement

REACTJS how to load a page at the end of timeout?

Im new to REACTJS and trying to make a webpage for practice. I can’t figure out how to load a new page at the end of timeout.

Basically what I am trying to do is to make the Main page load and then start a timer for about 5 seconds and at the end of the 5 seconds I would like to load the next page.

Thanks 🙂

Advertisement

Answer

It all depends on your current setup.

First of all you will have a setTimeout in your component at all cost, the structure is like this :

setTimeout(() => {
  // Do some stuff here
}, secondsBeforeExecution)

Then inside that function you could use the window href to redirect to another page like this :

document.location.href = newUrl;

You could also use react-router which can be used to create different pages in your React app and switch to a different page easily. I would give this a shot : https://reactrouter.com/web/guides/quick-start

Once it’s set up you could do something like this :

const history = useHistory()

setTimeout(() => {
  history.push('/my/new/page')
}, 5000)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement