search

Home  >  Q&A  >  body text

React 6.4.0 Common headers for all routers

<p>I'm starting a React project using <code>react-router-dom</code> version 6.4.0 but I can't create a common header for all routes. </p> <p>App.js - This is the file where I added <code>RouterProvider</code></p> <pre class="brush:php;toolbar:false;">import logo from './logo.svg'; import './App.css'; import { Link, Outlet, RouterProvider } from "react-router-dom"; import { routers } from "./routes/routes"; function App() { return ( <RouterProvider router={routers}> <div>Header</div> <Outlet /> </RouterProvider> ); } export default App;</pre> <p>routes.js - In this file I will create all the routes</p> <pre class="brush:php;toolbar:false;">import { createBrowserRouter, redirect } from "react-router-dom"; import About from "../pages/About/About"; import Home from "../pages/Home/Home"; import { getUser, isAuthenticated } from "../sso/authUtil"; const authLoader = () => { if (!isAuthenticated()) { return redirect("https://google.com"); } else { return getUser(); } }; export const routers = createBrowserRouter([ { path: "/", element: <Home />, loader: authLoader, }, { path: "/about", element: <About />, }, ]);</pre> <p>Home.js - This file is the home page and contains links to other pages as well as the title</p> <pre class="brush:php;toolbar:false;">import React from "react"; import { Link, Outlet, useLoaderData } from "react-router-dom"; const Home = () => { const loaderData = useLoaderData(); return ( <> <div>Header</div> <Link to="/">Home</Link> <Link to="/about">About</Link> <div>Home: {loaderData}</div>{" "} <Outlet /> </> ); } export default Home;</pre> <p>About.js - This is a normal component that represents about</p> <pre class="brush:php;toolbar:false;">import React from "react"; const About = () => { return <div>About</div>; }; export default About;</pre> <p>I want the <code>Home</code> and <code>About</code> components to have the title at the top when they load. </p>
P粉864872812P粉864872812461 days ago498

reply all(1)I'll reply

  • P粉909476457

    P粉9094764572023-08-26 13:52:56

    Even in react-router-dom@6.4.0, routing with generic UI rendering layout still works fine.

    Create a layout route component that renders the public header component and an Outlet for nested routes.

    Example:

    const Layout = () => (
      <>
        <CommonHeader />
        <Outlet />
      </>
    );

    Import and render Layout on the layout route in the configuration.

    const routers = createBrowserRouter([
      {
        element: <Layout />,
        children: [
          {
            path: "/",
            element: <Home />,
            loader: authLoader
          },
          {
            path: "/about",
            element: <About />
          }
        ]
      }
    ]);

    ...

    function App() {
      return <RouterProvider router={routers} />;
    }

    reply
    0
  • Cancelreply