How to Create a Collapsible Sidebar
In Docusaurus, you can enhance the user experience by allowing readers to collapse the sidebar to focus on the content. This is achieved through specific configurations in your docusaurus.config.js file.
1. Enabling the Sidebar Collapse Button
The "Hideable Sidebar" feature adds a small button (usually <<) at the bottom of the sidebar. When clicked, the sidebar slides away, and a small expand button takes its place.
Configuration
Open your docusaurus.config.js and look for the themeConfig section. Ensure hideable is set to true within the docs.sidebar object:
themeConfig: {
docs: {
sidebar: {
hideable: true, // This enables the collapse button
},
},
// ... other configs
}
2. Auto-Collapsing Categories
If you have many categories (folders) in your sidebar, it can become cluttered. You can enable autoCollapseCategories so that when a user opens one category, all other open categories automatically close.
Configuration
Add autoCollapseCategories: true to the same sidebar configuration block:
themeConfig: {
docs: {
sidebar: {
hideable: true,
autoCollapseCategories: true, // Only one category stays open at a time
},
},
}
3. Sidebar Persistence
Docusaurus remembers the user's sidebar state (open, closed, or specific categories expanded) using local storage in their browser. This means if they refresh the page, the sidebar will remain in the state they left it.
4. Troubleshooting
If you don't see the collapse button after changing the configuration:
- Restart the Container: Sometimes the config changes require a full restart.
sudo docker restart docusaurus
- Check CSS: Ensure you haven't accidentally hidden the collapse button with custom CSS in
src/css/custom.css. The class for the button is usually.collapseSidebarButton_.... - Browser Cache: Perform a hard refresh (
Ctrl + Shift + R).
Summary of Settings
| Setting | Type | Description |
|---|---|---|
hideable | boolean | Adds the expand/collapse button at the bottom. |
autoCollapseCategories | boolean | Automatically collapses siblings when a category is expanded. |
collapsed | boolean | (In _category_.json) Sets if a specific category is closed by default. |