1

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?

0

1 Answer 1

2

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');
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.