Home > Blockchain >  header to be show only in "/" and "/checkout" react reuter dom
header to be show only in "/" and "/checkout" react reuter dom

Time:12-04

I want to be visible only during '/checkout' and '/' instead of in the whole path. it is being difficult to do in react reuter dom v6.

import React from "react";
import "./App.css";
import Header from "./Header";
import Home from "./Home";
import Checkout from "./Checkout";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Login from "./Login";

function App() {
  return (
    // BEM
    <BrowserRouter>
      <div className="app">
        <Header />
        <Routes>
          <Route path="/" element={<Home />}></Route>
          <Route path="/checkout" element={<Checkout />}></Route>
          <Route path="/login" element={<Login />}></Route>
        </Routes>
      </div>
    </BrowserRouter>
  );
}

export default App;

CodePudding user response:

You can use useLocation() hook in Header component and check pathname for needed conditions for rendering.

Header.js

  import { useLocation } from "react-router-dom";
  ....
  const { pathname } = useLocation();

JSX

return (
  <div>
     {!pathname.includes("login") && <div>Not Login page</div>}
  </div>
)

CodePudding user response:

On react-router v6 you can make Layout for specific routes. You can add <Outlet/> to detect all route child like code below. Documentation React-Router

function App() {
  return (
    // BEM
    <BrowserRouter>
      <div className="app">
        <Routes>
          <Route path="/" element={<Layout/>}>
               <Route path="/" element={<Home />}></Route>
               <Route path="/checkout" element={<Checkout />}></Route>
          </Route>
          <Route path="/login" element={<Login />}></Route>
        </Routes>
      </div>
    </BrowserRouter>
  );
}

Code for Layout.jsx

import {Outlet} from "react-router"

const Layout = () => {

    return (
        <>
            <Header/>
            <Outlet/>
        </>
    )
}

export default Layout;
  • Related