Show default component in Outlet

Viewed 152

How can I show a default component in an Outlet? I have the following in index.js:

ReactDOM.render(
  <React.StrictMode>
      <BrowserRouter>
          <Routes>
              <Route path="/" element={<App/>}>
                  <Route path="page1" element={<Page1/>}/>
                  <Route path='page2' element={<Page2/>}/>
              </Route>
          </Routes>
      </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);

Here's App.js:

function App() {
  return (
    <div className="App">
        <Link to='/'>Home</Link> {' '}
        <Link to='/page1'>Page 1</Link> {' '}
        <Link to='/page2'>Page 2</Link>

        <main>
            <Outlet/>
        </main>
    </div>
  );
}

When I click on either the Page 1 or Page 2 link, components Page1 or Page are displayed in the Outlet. When at the root route ("/"), I want to display a default component, like <p>Home</p> in the Outlet.

1 Answers

The Outlet components is used to render the child route contents only, it is a kind of placeholder. Since there is no content other than the Outlet, nothing will be rendered in the / route other than the links.

ReactDOM.render(
  <React.StrictMode>
     <BrowserRouter>
        <App/>
    </BrowserRouter>
  </React.StrictMode>,
 document.getElementById('root')
);

function App() {
   return (
     <div className="App">

       <nav>
         <Link to='/'>Home</Link> {' '}
         <Link to='/page1'>Page 1</Link> {' '}
         <Link to='/page2'>Page 2</Link>
       </nav>

        <Routes>
           <Route path="/" element={<Home/>} />
           <Route path="page1" element={<Page1/>}/>
           <Route path='page2' element={<Page2/>}/>
        </Routes>
    </div>
    );
   }
Related