skip to Main Content

I’m using react with react router for the client-side routing.
I have a header, outlet, and footer.
What I want is to give the Outlet a classname so that every component get’s a margin-top.
Is there a way to do this or do I have to make a wrapper component surrounding the Outlet?

2

Answers


  1. The <Outlet component of the React Router Dom does not have a className prop. If you want to apply a style to the component that would eventually replace the Outlet component placeholder, then you should wrap the Outlet with an HTML element and pass your className or style prop to the HTML element and subsequently pass in the appropriate class that applies margin-top to it.

    Login or Signup to reply.
  2. I have a header, outlet, and footer. What I want is to give the Outlet
    a classname so that every component get’s a margin-top. Is there a way
    to do this or do I have to make a wrapper component surrounding the
    Outlet?

    The Outlet component itself is not any component or HTML element that takes a className prop nor is it visually rendered to the screen. It’s effectively an invisible container for nested routes to render their element content in.

    See Outlet: The only prop available is the context prop it can provide.

    interface OutletProps {
      context?: unknown;
    }
    declare function Outlet(
      props: OutletProps
    ): React.ReactElement | null;
    

    Any UI styling you want applied should be implemented in the layout route component rendering the Outlet. Yes, you will need to wrap the Outlet in something that is styleable.

    Trivial Example:

    const AppLayout = () => (
      <div>
        <Header />
        <div style={{ marginTop: "2rem" }}>
          <Outlet />
        </div>
        <Footer />
      </div>
    );
    
    <Routes>
      <Route element={<AppLayout />}>
        {/* Routes with header, footer, and margin-top applied */}
      </Route>
      {/* Route without header, footer, and no margin-top */}
    </Routes>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search