reactjsreact-router-domvite

React + Vite always redirect route to another route


I have a React + Vite app with multiple routes. I also have a few static HTML pages and assets in the public folder (including home.html).

I'd like to have the index route to point to home.html. The code below loads and points to "http://localhost:4173/home" but the page isn't loading. Refreshing the page loads the html page.

What am I missing?

function App() {
  return (
    <Routes>
      <Route path="/" element={<Layout />}>
        <Route index element={<Navigate to="/home" replace />} />
        <Route path="blog" element={<Blog />} />
        <Route path="about" element={<About />} />
      </Route>
    </Routes>
  )
}

I was expecting the app to load and point to "http://localhost:4173/home" and show that page.

The URL is pointing to the correct URL but the page isn't loading until I hit refresh in the browser.


Solution

  • React-Router-DOM handles all routing and navigation actions client-side, so the code is attempting to redirect to a "/home" route that is rendered within by App. In other words, these are internal navigation actions. When you reload the page a request is made to the server for the page and the correct content is returned in the response back to the client.

    What you are describing would be an external navigation action. I suggest creating a "home page" component that basically reloads the page to your "http://localhost:4173/home.html" page.

    Example:

    const RedirectHomePage = () => {
      // Redirect & reload page
      React.useEffect(() => {
        window.location.href = "/home";
      }, []);
    
      return null;
    };
    
    function App() {
      return (
        <Routes>
          <Route path="/" element={<Layout />}>
            <Route index element={<RedirectHomePage />} />
            <Route path="blog" element={<Blog />} />
            <Route path="about" element={<About />} />
          </Route>
        </Routes>
      );
    }