Search code examples
javascriptreactjsjsxreact-router-dom

how to render home and header files together while routing using react


I am trying to make an ecommerce web app using React. I have made the home page, now while routing. I am unable to render home and header files together. I have nested the home route under the header route. I have set the path for the header to be the default (path = '/') and I have set the home to be the index element.

This is my code now. When I run this only the header gets rendered.

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Header from './Header'
import Home from './Home'
import './App.css'

function App() {
  return (
    <Router>
      <div className="app">
        <Routes>
          <Route path='/' element={<Header />}>
            <Route index element={<Home />} />
          </Route>
        </Routes>
      </div>
    </Router>
  );
}

export default App;

Solution

  • If you would like to render a layout route to share some common UI elements/components, then the layout route component necessarily should render an Outlet component for the nested routes to be able to render out their element content.

    Either of the following should work:

    1. Update Header to render an Outlet component.

      import {
        ....
        Outlet,
      } from 'react-router-dom';
      
      const Header = () => {
        ...
      
        return (
          <>
            {/* Header UI */}
            <Outlet />
          </>
        );
      };
      
    2. Create a new layout route component that renders Header and an Outlet.

      import {
        BrowserRouter as Router,
        Routes,
        Route,
        Outlet
      } from "react-router-dom";
      import Header from './Header';
      import Home from './Home';
      import './App.css';
      
      const AppLayout = () => (
        <>
          <Header />
          <Outlet />
        </>
      );
      
      function App() {
        return (
          <Router>
            <div className="app">
              <Routes>
                <Route path='/' element={<AppLayout />}>
                  <Route index element={<Home />} />
                </Route>
              </Routes>
            </div>
          </Router>
        );
      }
      

    For more information: