Home > database >  How to find out which Router component is being rendered in React?
How to find out which Router component is being rendered in React?

Time:06-04

I have a Navbar component and I am trying to render it with different CSS styles using styled-components with respect to the component route which is being rendered. How can I check if that component is being rendered or not ?

const NavbarContainer = styled.div`
  height: 115px;
  font-family: 'Domine', serif;
  align-content: center;
  align-items: center;
  position: absolute;
  z-index: 4;
  width: 100vw;
  overflow: hidden;

  &:hover {
    background-color: white;
    color: black !important;
  }
`;

lets say this the component and I want to change position: absolute to position: static in Login page but I want that to stay that as position: absolute in the home page. How can I achieve this?

CodePudding user response:

One idea would be to wrap your component inside another like In Login page

const NavWrapper = styled.div`
>div{
 position: static 
}
`
<NavWrapper>
<NavbarContainer/>
</NavWrapper>

CodePudding user response:

You can achieve this with conditional styled based on login path

<Appbar style={{ position: pathname === '/login' ? 'static' : 'absolute' }}></Appbar>

CodePudding user response:

Create a version of the NavbarContainer specific for the login route and override the position rule, and use layout routes to render the appropriate routes with the appropriate layout/navbar.

Example:

const NavbarContainer = styled.div`
  height: 115px;
  font-family: 'Domine', serif;
  align-content: center;
  align-items: center;
  position: absolute;
  z-index: 4;
  width: 100vw;
  overflow: hidden;

  &:hover {
    background-color: white;
    color: black !important;
  }
`;

const StaticNavbarContainer = styled(NavbarContainer)`
  position: static;
`;

...

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

const NavbarLayout = ({ children }) => (
  <>
    <NavbarContainer>{children}</NavbarContainer>
    <Outlet />
  </>
);

const StaticNavbarLayout = ({ children }) => (
  <>
    <StaticNavbarContainer>{children}</StaticNavbarContainer>
    <Outlet />
  </>
);

...

<Routes>
  <Route
    element={(
      <NavbarLayout>
        // ... render links here as children
      </NavbarLayout>
    )}
  >
    <Route path="/" element={<Home />} />
    // ... routes to render with absolute positioned navbar
  </Route>

  <Route
    element={(
      <StaticNavbarLayout>
        // ... render links here as children
      </StaticNavbarLayout>
    )}
  >
    <Route path="/login" element={<Login />} />
    // ... other routes with static positioned navbar
  </Route>

  // ... other routes without navbars
</Routes>
  • Related