In react how do I automatically open another page?

Viewed 479

I am new to React and finding it hard to Google (generic terms like open page!) what should be a common scenario.

My code renders a page containing a link using Linkify:

<Linkify properties={{target: '_blank'}}>{someText}</Linkify>

where someText contains a link to an external site. This opens in a new tab when clicked.

Is there an example of how to automatically (ie no click required) pop up this link in a new tab, after a few seconds delay?

2 Answers

Try this:

<Linkify
  componentDecorator={(
    decoratedHref: string,
    decoratedText: string,
    key: number
  ) => (
    <a href={decoratedHref} key={key} target="_blank">
      {decoratedText}
    </a>
  )}
>
  {someText}
</Linkify>;

The solution is very simple. Try setTimeout(). The setTimeout() method will call a function or execute a piece of code after a time delay (in millisecond). Here the called function is window.loacation.href, which will have the URL of the page (you wish to redirect).

 const redirect_Page = () => {
        let tID = setTimeout(function () {
            window.location.href = 
            "https://stackoverflow.com/"; //replace with your url
            window.clearTimeout(tID);// clear time out.
        }, 5000);
    }

I hope this will help you. All the best

Related