Redirect to External Link in React Router
When managing routes in a React app using React Router, it may become necessary to redirect users to an external resource. For instance, a privacy policy page may need to redirect to a hosted document on Zendesk.
While a JavaScript-based solution can be implemented directly in the index.html file, React Router offers a more elegant approach with the following line of code:
<Route path="/privacy-policy" component={() => { window.location.href = "https://example.com/1234"; return null; }} />
This solution utilizes the React pure component concept, encapsulating the redirection logic in a single function. Instead of rendering anything, this function redirects the browser to the external URL.
This approach is compatible with both React Router 3 and 4, providing a convenient way to redirect users from within the controlled routing system.
The above is the detailed content of How to Redirect to an External Link with React Router?. For more information, please follow other related articles on the PHP Chinese website!