Advanced Manual

Hide Sidebar Conditionally

EdgeSidebar and InsetSidebar builder provide utility function to hide sidebar at specific breakpoints.

Take this configuration as an example.

const scheme = Layout();

scheme.configureEdgeSidebar(builder => {
  builder
    .create('primarySidebar', { anchor: 'left' })
    .registerTemporaryConfig('xs', {
      anchor: 'left',
      width: 'auto', // 'auto' is only valid for temporary variant
    })
    .registerPermanentConfig('md', {
      width: width, // px, (%, rem, em is compatible)
      collapsible: true,
      collapsedWidth: 64,
    });

  builder.hide('primarySidebar', ['xl']);
});

inside configuration callback, you can call builder.hide to specifically hide sidebar at target breakpoints. The breakpoints you provide will not follow mobile first approach which means ["sm"] will hide only for sm breakpoint.

hidden means Sidebar is still rendered in the page but with display: none.

hide function accept 2 parameters.

type hide = (sidebarId: string, breakpoints: boolean | Breakpoint[]) => void;
  • builder.hide("primarySidebar", true) = sidebar id: “primarySidebar” is hidden at all breakpoints.
  • builder.hide("sidebarA", ["xs"]) = sidebar id: “sidebarA” is hidden only at xs breakpoint (~0-599px)
  • builder.hide("sidebarB", ["md", "xl"]) = sidebar id: “sidebarB” is hidden only at md and xl (not include lg)

By understanding this logic we can hide sidebar based on specific path same as what mui-treasury homepage does.

In this demonstration, I will use react-router-dom as routing provider.

in index.js, wrap the App with BrowserRouter. for more info, read react-router quick start

Next, in App.js. I declare routes inside Content to navigate between pages(try clicking between pages) and then I import useLocation (a react hook from react-router-dom) to get the current location. When route changes our App will rerender and location will be different. This is all about react not mui-layout. If you wonder how functional component works, read this article from Dan Abramov

Finally add builder.hide conditionally when location.pathname === '/'

const Dashboard = () => {
  const location = useLocation();
  scheme.configureEdgeSidebar(builder => {
    builder
      .create('primarySidebar', { anchor: 'left' })
      .registerPermanentConfig('xs', {
        width: 200, // px, (%, rem, em is compatible)
        collapsible: true,
        collapsedWidth: 64,
      });
    if (location.pathname === '/') {      builder.hide('primarySidebar', true);    }  });
  return <Root scheme={scheme}>...</Root>;
};

or you can switch the statement like this.

// instead of if
// if (location.pathname === "/") {
//  builder.hide("primarySidebar", true);
// }

builder.hide('primarySidebar', location.pathname === '/');

Try it your self. If you use InsetSidebar and want to hide it conditionally, the api is the same.