Home > Software design >  Redirect to external link from React app using react-router-dom
Redirect to external link from React app using react-router-dom

Time:07-12

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

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?

CodePudding user response:

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');
}
  • Related