Home > Mobile >  React 6.4.0 common header for all the router
React 6.4.0 common header for all the router

Time:09-21

I am starting react project with react-router-dom version 6.4.0, but not able to create common header for all the routes.

App.js - This is the file where I am adding RouterProvider

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;

routes.js - In this file I am going to create all the routes

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 />,
  },
]);

Home.js - This file is home page which will have the links to other pages along with header

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;

About.js - It is normal component which say about

import React from "react";

const About = () => {
  return <div>About</div>;
};

export default About;

I want both Home and About component to be loaded with header on top.

CodePudding user response:

Even in [email protected] rendering layout routes with common UI still works the same.

Create a layout route component that render the common header component and an Outlet for nested routes.

Example:

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

Import and render Layout on a 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} />;
}

Edit react-6-4-0-common-header-for-all-the-router

  • Related