Skip to content

TOC does not work when importing one MDX into another #3915

Closed

Description

@oriooctopus

🐛 Bug Report

On our site we have a couple of duplicate doc pages. To avoid repeating content we have one doc as the source of truth then import the content like so:

import Content from './doc1.md';

<Content />

The issue is, the table of contents is not picked up on the pages that import the content. Please let me know if there is a better way to handle duplicate pages and if this usage is just conceptually wrong

Have you read the Contributing Guidelines on issues?

Yes

To Reproduce

npx @docusaurus/init@latest init my-website classic

in doc2:

import Content from './doc1.md';

<Content />

It's worth noting that this also happens on my 6 month old version, so I don't think that it's due to anything recent

Activity

  1. added
    bug
    status: needs triage
    on Dec 14, 2020
  2. slorber commented on Dec 14, 2020

    @slorber
    Collaborator

    This usage should be supported, but it's a current limitation of the existing system.

    Unfortunately, I'm not sure how to implement this technically, and still busy on i18n.

    In the meantime I'd recommend to only put raw text in mdx and duplicate the headings. That's not ideal but I don't have any other solution for now 😓

    You could also add a build script that copy a file to multiple locations, or use a remark plugin that substitute a placeholder with a content string in multiple docs

  3. oriooctopus commented on Dec 15, 2020

    @oriooctopus
    ContributorAuthor

    How difficult would it be to fix? I could possibly put up a PR

  4. slorber commented on Dec 15, 2020

    @slorber
    Collaborator

    @oriooctopus unfortunately I suspect this to be quite complex to implement, and can't even give you much help to do so because I'm not sure how this should be done.

    You can look at the code in this folder: packages/docusaurus-mdx-loader/src/remark/toc
    If you are comfortable with ASTs and visitors you can give it a try

  5. jknoxville commented on Dec 16, 2020

    @jknoxville
    Contributor

    @slorber I think we can address this by getting docusaurus-mdx-loader to follow jsx tags into their imported sources when traversing the AST.

    I did something similar to this before, using the fs api to read the file and getting remark to parse this in-place of the jsx node (so you can continue to recurse into the imported file and visit its nodes).

    The only downside in my eyes is that we'd be using the node fs api, which means this package wouldn't work at runtime in the browser anymore (if it does now).

    Do you think this would be an acceptable change?

  6. slorber commented on Dec 16, 2020

    @slorber
    Collaborator

    Yes @jknoxville this is what I have in mind: a recursive visitor that is able to "flatten" the TOC structure of multiple MDX docs (and preserve the correct TOC ordering).

    This code already runs in node (it's a Webpack loader)

  7. oriooctopus commented on Jan 19, 2021

    @oriooctopus
    ContributorAuthor

    @jknoxville do you still have any interest in fixing this? If not, maybe we could sync on what you had in mind and I might be able to implement it?

  8. jknoxville commented on Jan 20, 2021

    @jknoxville
    Contributor

    @oriooctopus I'm interested, but it's not top of my queue right now, so feel free to take a stab!

    Here's a prototype I made a while ago, for a remark plugin that effectively re-implements mdx transclusions by parsing the target of any imported markdown files, and then replacing any JSX nodes that use it, with the nodes of the target AST.
    https://gist.github.com/jknoxville/8ed4cb8bcef348362a99dd70bb8006ae

    It's scrappy, and not production-ready (currently uses eval for one thing - I'd recommend using babel to parse the imports instead), but it works. Maybe there's a more elegant way to do it.

    What I imagine, is modifying search.js to do what that prototype does before it starts visiting headings to assemble its TOC.

    I haven't tried this, but don't see why it wouldn't work.

  9. slorber commented on Jan 20, 2021

    @slorber
    Collaborator
  10. Laptopmini commented on Apr 30, 2021

    @Laptopmini
  11. slorber commented on Apr 30, 2021

    @slorber
  12. Laptopmini commented on Apr 30, 2021

    @Laptopmini
  13. Laptopmini commented on May 4, 2021

    @Laptopmini
  14. sweeneyskirt-sl commented on May 5, 2021

    @sweeneyskirt-sl
  15. 41 remaining items

  16. anatolykopyl commented on Dec 29, 2023

    @anatolykopyl
    Contributor

    I submitted a PR for Docusaurus v2, that I'll be willing to work on, but in the meantime, until it is accepted, I made a quick drop in replacement remark plugin that fixes this behaviour: @akopyl/docusaurus-toc-patcher.

    It implements the logic from shuding/nextra#2199.

  17. slorber commented on Jan 19, 2024

    @slorber
    Collaborator

    This has been fixed (main/canary) as part of #9684, and will be released in Docusaurus v3.2

    Thanks for the inspiration @dimaMachina and the initial port @anatolykopyl 🤗

  18. jbltx commented on Jan 29, 2024

    @jbltx

    Nice feature, do you plan to also support headings from custom JSX/TSX components to appear in ToC ? I have a React component that reads a JSON file and create headings and paragraphs based on it (the JSON file is loaded as a module but I guess it means the ToC should be generated dynamically at runtime and not at compile time?)

  19. slorber commented on Feb 1, 2024

    @slorber
    Collaborator

    @jbltx we only support importing other MDX files atm

    However, it could be technically possible to also support React imported components, and try to get the compiler to output something looking like this:

    import Partial, 
      {toc as __tocPartial} from "_partial.mdx"
    import MyComponent from "MyComponent"
    
    # Doc
    
    ## Doc heading
    
    <Partial/>
    
    <MyComponent/>
    
    export const toc = [
      {
        "value": "Doc heading",
        "id": "doc-heading",
        "level": 2
      }, 
      ...__tocPartial,
      ...MyComponent?.toc?.() 
    ] 

    Note that in any case, it would be your responsibility to implement the toc function attribute:

    const MyComponent = () => <h2 id="hello">Hello</h2>
    
    MyComponent.toc = () => {
      return [{id: "hello", value: "Hello", level: 2}];
    };
    
    export default MyComponent;

    We can't execute the React code and infer the TOC from that execution.

    Would that be a helpful addition, or is this too limited?

  20. jbltx commented on Feb 2, 2024

    @jbltx

    Would that be a helpful addition, or is this too limited?

    Thank you for the suggestion @slorber, I think your example is enough for my use case indeed! 👍

  21. felipecrs commented on Apr 12, 2024

    @felipecrs
    Contributor

    I don't know if I'm doing something wrong, but this is still not working for me, even after the fix:

    _release.mdx:

    ## Release {props.release}

    releases.mdx:

    import Release from "./_release.mdx"
    
    # Releases
    
    ## Top heading
    
    {["v1", "v2", "v3"].map((release) => <Release release={release} />)}

    And the result:

    image

  22. slorber commented on Apr 12, 2024

    @slorber
    Collaborator

    @felipecrs this is unlikely we will ever support this. The TOC is computed statically at MDX compilation time. We are not running the JS to see what the output is and if it contains any heading. Hence we don't support such loop, nor using props inside partial headings.

    If you want that, you'd have to use the TOC function form described just above, a possible enhancement that we haven't implemented yet.

  23. felipecrs commented on Apr 12, 2024

    @felipecrs
    Contributor

    @slorber I see.

    Implementing my own toc function is 100% acceptable for my use case, I would appreciate this capability.

  24. felipecrs commented on Apr 12, 2024

    @felipecrs
    Contributor

    Ops, sorry, did you mean that I could already implement my toc function?

    I tried it with:

    import Release from "./_release.mdx"
    
    # Releases
    
    ## Top heading
    
    {["v1", "v2", "v3"].map((release) => <Release release={release} />)}
    
    export const toc = () => ["v1", "v2", "v3"].map((release) => ({
      "value": `Release ${release}`,
      "id": `release-${release}`,
      "level": 2
    }))

    And then the toc disappeared entirely. (Also tried toc = [] like in one of the examples)

  25. slorber commented on Apr 13, 2024

    @slorber
    Collaborator

    @felipecrs we don't support a toc function yet, only a toc array export.

    You should rather do that instead of a loop

    import ReleaseV1 from "./_releaseV1.mdx"
    import ReleaseV2 from "./_releaseV2.mdx"
    import ReleaseV3 from "./_releaseV3.mdx"
    
    # Releases
    
    ## Top heading
    
    <ReleaseV1/>
    
    <ReleaseV2/>
    
    <ReleaseV3/>

    Note, we don't support "dynamic headings" such as ## Release {props.version}, so you will need to provide a TOC export if you want dynamic headings (you can provide the toc export either on the root doc or the partial). There's also a non-implemented proposal to solve that problem that you can track here: #9773

  26. felipecrs commented on Apr 13, 2024

    @felipecrs
    Contributor

    Great. Thank you, I'll watch the pull request, because my data is very dynamic so I can't define them statically.

  27. added a commit that references this issue on Jul 17, 2024
  28. todo0123 commented on Oct 16, 2025

    @todo0123

    Hi guys,

    Unfortunately, this issue still isn't fixed, and I can add a note that <h1>..<h6> tags aren't added either. I know this behavior is described in the docs (that only MD headings go to the ToC), but I have a proposal.

    What if the ToC were fully a client-side JS component?
    This right ToC sidebar has nothing to do with either SEO or the main content, so we can safely remove it from static generation.

    Then, a JS script added to the page could scan all the headings on the page and build the ToC on the fly!

    The ToC would contain headings:

    • included from any .tsx or .mdx components
    • defined in MD or HTML formats
    • inside or outside React code

    No complicated server-side parsing, no struggling with preprocessing sequences.

    It would be better to allow components to exclude certain H1..H6 elements from the ToC if needed using an attribute like data-include-to-toc="false", but include every existing heading written in all possible forms in the ToC by default.

    Any pitfalls?
    What do you think?

  29. slorber commented on Oct 17, 2025

    @slorber
    Collaborator

    Unfortunately, this issue still isn't fixed

    The issue as originally described is fixed. If something is not, that must be something slightly different, and you'd rather provide a repro so that we can understand your exact setup.

    I can add a note that <h1>..<h6> tags aren't added either.

    We only add to TOC Markdown headings, not JSX nodes that produce headings.

    If you think that could be useful, feel free to open a separate proposal. It isn't really related to this issue which is about importing one MDX into another.

    I know this behavior is described in the docs (that only MD headings go to the ToC), but I have a proposal.

    What if the ToC were fully a client-side JS component? This right ToC sidebar has nothing to do with either SEO or the main content, so we can safely remove it from static generation.

    Then, a JS script added to the page could scan all the headings on the page and build the ToC on the fly!

    The ToC would contain headings:

    • included from any .tsx or .mdx components
    • defined in MD or HTML formats
    • inside or outside React code

    No complicated server-side parsing, no struggling with preprocessing sequences.

    It would be better to allow components to exclude certain H1..H6 elements from the ToC if needed using an attribute like data-include-to-toc="false", but include every existing heading written in all possible forms in the ToC by default.

    Any pitfalls? What do you think?

    We purposefully don't want that.

    Having the TOC magically appear after the page loads and React hydrates wouldn't give a very good UX.

    Note that if you believe this tradeoff is acceptable for your site, you can already swizzle the TOC component and build this yourself in a React useEffect instead of using the TOC items provided as props.

    Since this is possible to achieve in userland today, I'd suggest that you code this on your site, deploy it to production, and send us the link for the community to see how it behaves.

    If there's traction for your proposed solution after seeing it in action, we could eventually design a "toc mode" feature that allows you to opt in for client-side generation. I doubt we'll make it the default mode, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugdifficulty: advanceddomain: markdown

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions