React router Dom – how to redirect to an external link?

Total
0
Shares

You can redirect to an external link in react router dom from Component prop of Route. As you know, you can load a component for a route by declaring it in Component prop. To redirect to an external link, we can simply put the link in window.location.href. Check out the code –

<Route path='/some-path' component={() => { 
     window.location.href = 'link_to_redirect_to'; 
     return null;
}}/>

Also, you can create a temporary link and programmatically click on it –

<Route path='/some-path' component={() => { 
  var link = document.createElement('a');
  link.href = 'link_to_redirect_to';
  document.body.appendChild(link);

  link.click();
  return null;
}} />

    Tweet this to help others

Live Demo

Open Live Demo