Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Redirect to external link from React app using react-router-dom

What I want is when entering the '/' path, it renders the homepage (App.js), and I create a special link to redirect to an external page

import React from 'react';
import { Routes, Route } from 'react-router-dom';
import App from './App';

const Home = () => { 
    return (
        <Routes>
            <Route path="/" element={<App />} />
            <Route path="/g" element={() => window.location.replace('https://google.com')} />
        </Routes>
    )
}

export default Home;

Result:

  • http://localhost:3004/ doesn’t load the homepage and shows a blank
    page instead
  • http://localhost:3004/g doesn’t redirect, shows a blank page as above

So I tried to ditch the router and render the App directly, it’s still working

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React from 'react';
import { Routes, Route } from 'react-router-dom';
import App from './App';

const Home = () => { 
    return (
        <App />
    )
}

export default Home;

What did I do wrong?

>Solution :

The issue is that your Route still needs to have a JSX element as the element prop. So just make a function that has your window.location.replace on it.

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="g" element={<Redirect />} />
      </Routes>
    </BrowserRouter>
  );
}

function Home() {
  return 'Home';
}
function Redirect() {
  window.location.replace('https://google.com');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading