Search code examples
docusaurus

How do I customize the generated index page in Docusaurus?


I have a generated-index page, and I can see how to customize the on-page title and description in the category.json for the directory, but is there a way to customize the items generated by the files in the same directory? For example:

  • tutorials
    • _category_.json
    • 01-first-tutorial.md
    • 02-second-tutorial.md

I want to be able to have an icon for each of the files and different text than what is pulled from those files first paragraph like seems to be the default. What I want perhaps looks something like this page, but the icons and text need to be linked to the tutorial pages.

I have tried using a DocCardList, adding in descriptions, adding in items (failed), and changing each of my tutorial files, but so far, no love.


Solution

  • EDIT:

    They've come up with a new component called DocCardList which you can use in version 2.3.0.

    1. Create an index.mdx file in your category folder.

    2. Add the following:

      import DocCardList from '@theme/DocCardList';
      
      <DocCardList />
      
    3. Swizzle or otherwise override this component in your src/theme folder to add custom styling, etc.

    ORIGINAL ANSWER:

    Maybe you could try swapping the generated index component using the docCategoryGeneratedIndexComponent prop (link to reference). That would replace all auto-generated index pages which might be what you want.

    In docusaurus.config.js, in the presets section, add

    presets: [
        [
          "classic",
          /** @type {import('@docusaurus/preset-classic').Options} */
          ({
            docs: {
              sidebarPath: require.resolve("./sidebars.js"),
              docCategoryGeneratedIndexComponent:
                "@site/src/components/CategoryIndexPage",
            },
            // etc.
          }),
        ],
      ],
    

    And then try adding the following custom component under src/components/CategoryIndexPage.tsx:

    import React from "react";
    
    export default function CategoryIndexPage(props) {
      return (
        <pre>
          <code>{JSON.stringify(props, null, 2)}</code>
        </pre>
      );
    }
    

    This will just show you what the prop structure is in the component.

    When I looked in the theme component which generates this page, it uses

    const category = useCurrentSidebarCategory();
    

    But when I try that to get the list of items, I get the following error:

    Hook useDocsSidebar is called outside the .

    Maybe you can figure out the next steps, I was not able to. 😅

    Alternatively, you can create an index.mdx file in your category folder and import a custom React component into that. That gives me the same context violation error, though.

    # My custom category page
    
    Some Markdown content here.
    
    import CategoryIndex from "@site/src/components/CategoryIndex.tsx";
    
    <CategoryIndex />