skip to Main Content

I am using React Router for my website and I encountered following problem. I have defined my main App component as follows:

import './App.css'
import { Navbar } from './Navbar'
import { Outlet } from 'react-router'

function App() {
    return (
        <div>
            <Navbar />
            <Outlet />
        </div>
    )
}

export default App

and then I used this component for base route:

<BrowserRouter>
    <Routes>
        <Route path="/" element={<App />} >
            <Route path='home' element={<Home />} index />
            <Route path='about' element={<About />} />
        </Route>
        <Route path="*" element={<Navigate to="/Home" replace />} />
    </Routes>
</BrowserRouter>

Everything works well, I can navigate home and about pages, but when I navigate to /, it get blank page with Navbar, which is understandable, but I don’t know how I could display my default home page. Can I somehow instruct React to redirect to home ? I cannot set Home component for / route, as it would totally break the app (as App component has the Outlet component).

Libraries’ versions:

"react-dom": "^18.2.0",  
"react-router": "^6.21.1",  
"react-router-dom": "^6.21.1",

2

Answers


  1. Can you provide the react-router version that you are using?

    Login or Signup to reply.
  2. It seems you already know what causes the problem, just need a guidance with the redirect part.

    As you already mentioned, the code is working as intended. Looking at your structure, there are no children configured to be rendered when the path "/" is matched. To fix this, you have to use both index attribute and trigger a navigation to "/home" when path "/" is accessed.

    To do this:

    <BrowserRouter>
    <Routes>
        <Route path="/" element={<App />} >
            <Route index element={<Navigate replace to="/home" />} />
            <Route path='home' element={<Home />} />
            <Route path='about' element={<About />} />
        </Route>
        <Route path="*" element={<Navigate replace to="/home" />} />
    </Routes>
    

    Notice the line I added:

     <Route index element={<Navigate replace to="/home" />} />
    

    This new route has index attribute, and also uses <Navigate> component provided by react-router.

    1. index attribute: This attribute makes this route the default route for the parent, which is "/" in your case.

    2. <Navigate>: Here in your example, we can’t render <Home> directly, as you specifically requested not to do so:

      I cannot set Home component for / route, as it would totally break the app (as App component has the Outlet component).

      So it will redirect every "/" path to "/home" instead.

    Although this will most probably fix the issue you are facing, I strongly suggest that you use a non-empty "/" and do the routing there. In most cases, "/" is the home, rather than "/home".

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search