React-router External link
For an external site link in React, forget React Router and embrace the straightforward <a>
tag with the URL you desire:
With target="_blank"
, your link pops up in a new tab. The rel="noopener noreferrer"
attribute is like your security guard, keeping the new site isolated from your original page. It's React's version of locking the door when you leave the house.
Crystal clear ways for external redirection
Function component for redirection
When you are dealing with redirection and need to apply some logic before the "launch", use a function component. Imagine this function component as your personal launch controller:
Security rules for opening new tabs
Security first! When using an a
tag, remember to include noopener noreferrer
in the rel
attribute. We don't want any crafty tab-nabbing:
Using React Router's <Link>
for external links
If you miss the feel of React Router, worry not! Use the full URL in the <Link>
component's to
property. It's the soft chime of homely feels in a world full of <a>
tags:
Don't forget, target="_blank"
will open the URL in a new tab.
Navigating outside React components
In situations where we want to perform navigation from non-component logic (like a Redux action creator bossing around), use window.location.href
. This hunkers down directly at the low-level JavaScript, bypassing React Router and its nuances:
Esoteric Redux - extra handling for external URLs
Class components still got the game for redirection
Even in the world of functional components and hooks, React's class components hold their ground. When using class components, componentDidMount
makes an excellent spot for external redirects:
The window.location.replace
is our sneaky friend. It behaves as a redirect without creating a history entry.
Respecting user privacy - No leaks allowed!
In the wild world of the web, your user's privacy is paramount. Always use the rel='noreferrer'
attribute when creating a
tags leading to external sites. It keeps the referer header leak in check:
The difference between direct and safe navigation
The window.open
function opens external links in new tabs. However, it might act like a wild stallion unless tamed correctly:
The little quirks of React Router versions
When you're seeking a custom <Redirect>
solution, pay heed to the different versions of React Router. The classic React Router v3 may simplify custom redirection with <Redirect>
, whereas v4 could pose challenges and might require additional dependencies or configurations.
Was this article helpful?