Home > Enterprise >  React Router v6.4.5, redirect on page load
React Router v6.4.5, redirect on page load

Time:12-09

Looking for some help in regards to redirecting. Below are the code snippets.

index.js

const router = createBrowserRouter([

  {
    //set App as root element...
    path: "/",
    loader: () => {

    },
    element: <App/>,
    errorElement: <ErrorPage/>,

    //set routes for child elements...
    children: [
      {
        path: "/home",
        element: <Home/>
      },
      {
        path: "/about",
        element: <About/>,
        errorElement: <ErrorPage/>
      },  
      {
        path: "/blog",
       element: <Blog/>,
       errorElement: <ErrorPage/>
      },
      {
        path: "/services",
        element: <Services/>,
        errorElement: <ErrorPage/>
      }

    ]
  }
])

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <RouterProvider router={router} />
    {/* <App /> */}
  </React.StrictMode>
);

App.js

import React from "react";
import { BrowserRouter, Outlet, redirect, Route, Routes } from "react-router-dom";
import Navbar from "./components/Navbar";
import Home from "./views/Home";


function App() {

  return (

    <div className="App">
      <Navbar/>
      <Outlet/> 
    </div>
  );
}

export default App;

All I want to do is have the page redirect from 'localhost:3000/' when the page loads './' as the root to 'localhost:3000/home' so I can render the applications home page. Where I am using an outlet I want it to render there and have the navbar render at all times. I don't see an option in the docs for createBrowserRouter for a redirect.

CodePudding user response:

You can render a redirect from "/" to "/home" via the Navigate component and the replace prop.

Example:

const router = createBrowserRouter([
  {
    //set App as root element...
    path: "/",
    loader: () => { ... },
    element: <App />,
    errorElement: <ErrorPage />,

    //set routes for child elements...
    children: [
      {
        index: true, // <-- match on parent, i.e. "/"
        element: <Navigate to="/home" replace /> // <-- redirect
      },
      {
        path: "/home",
        element: <Home />
      },
      {
        path: "/about",
        element: <About />,
        errorElement: <ErrorPage />
      },  
      {
        path: "/blog",
       element: <Blog />,
       errorElement: <ErrorPage />
      },
      {
        path: "/services",
        element: <Services />,
        errorElement: <ErrorPage />
      }
    ]
  }
]);
  • Related