Home >Web Front-end >JS Tutorial >How to Redirect to External Links with React-Router?

How to Redirect to External Links with React-Router?

Barbara Streisand
Barbara StreisandOriginal
2024-11-06 16:48:02633browse

How to Redirect to External Links with React-Router?

How to Redirect to External Links Using React-Router?

RedirectLinks present a challenge in applications that employ React-Router for route management, as it operates within a single-page application (SPA) context. To tackle this, we present a solution that seamlessly redirects users to external resources.

Let's assume you wish to redirect users visiting /privacy-policy to example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies. While plain JavaScript can achieve this using an if statement, React-Router offers a more elegant approach.

Introducing a single-line solution:

<Route path='/privacy-policy' component={() => {
    window.location.href = 'https://example.com/1234';
    return null;
}} />

This React pure component concept condenses the component's code into a single function. Instead of rendering markup, it simply redirects the browser to the external URL.

The technique is compatible with both React Router 3 and 4, allowing you to effortlessly integrate external link redirection into your React-based applications.

The above is the detailed content of How to Redirect to External Links with React-Router?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn