Adding styles to Header component for particular Route

Viewed 114

This is my main app component in Reactjs:

function App() {
  return (
    <Router>
      <Header />
      <Switch>
        <div className="minht">
          <Route exact path="/" component={Home} />
          <Route path="/product/:id" component={Product} />
          <PrivateRoute path="/order/:id" component={Order} />
          <PrivateRoute exact path="/cart" component={Cart} />
          <Route exact path="/register" component={Register} />
          <Route exact path="/login" component={Login} />
          <PrivateRoute exact path="/address" component={AddAddress} />
          <PrivateRoute exact path="/checkout" component={Checkout} />
          <PrivateRoute exact path="/orderhistory" component={MyOrders} />
        </div>
      </Switch>
      <Footer />
    </Router>
  );
}

export default App;

i want to add some special styles to my Header component only when i am in /orderhistory route.

my header component where i want to append a new className or styles:

return (
    <div className="navsize">
      <Navbar dark expand="md" className="bg-dark ">
        <div className="col-12 col-md-6 text-center text-lg-left ">
          <NavbarBrand className="mr-3">
            <Link className="text-decoration-none" to="/">
              <h1 className="text-white">SHOPPING</h1>
            </Link>
          </NavbarBrand>
        </div>
        <div className=" col-12 col-md-6">
          <ul className="d-flex  justify-content-center justify-content-lg-end pl-0">
            {users.userAuth ? userLinks : authLinks}
          </ul>
        </div>
      </Navbar>
    </div>
  );
2 Answers

You can use the useRouteMatch React hook:

The useRouteMatch hook attempts to match the current URL in the same way that a would. It’s mostly useful for getting access to the match data without actually rendering a <Route>.

It returns null for non-matches, otherwise returns a match object.

import { useRouteMatch } from 'react-router-dom;

...

const orderHistoryMatch = useRouteMatch("/orderhistory");

const orderHistoryClass = orderHistoryMatch ? "orderHistory" : "";

Append the computed classname to the element you want to conditionally style.

Related