React-markdown: How to build automatic table of contents?

Created on 2 Nov 2017  路  1Comment  路  Source: remarkjs/react-markdown

Is there a possibility of automatic generation of header?

馃檵 typquestion

Most helpful comment

I did this using a custom renderer for the root element:

    root: ({ children }) => {
      const TOCLines = children.reduce((acc, { key, props }) => {
        // Skip non-headings
        if (key.indexOf('heading') !== 0) {
          return acc;
        }

        // Indent by two spaces per heading level after h1
        let indent = '';
        for (let idx = 1; idx < props.level; idx++) {
          indent = `${indent}  `;
        }

        // Append line to TOC
        // This is where you'd add a link using Markdown syntax if you wanted
        return acc.concat([`${indent}* ${props.children}`]);
      }, []);

      return (
        <div>
          <Markdown source={TOCLines.join("\n")} />
          {children}
        </div>
      );
    },

Basically it...

  1. Loops through the rendered child components of the <Markdown /> component
  2. Turns the headings back into Markdown
  3. Renders that using a nested <Markdown /> component

Seems to work!

>All comments

I did this using a custom renderer for the root element:

    root: ({ children }) => {
      const TOCLines = children.reduce((acc, { key, props }) => {
        // Skip non-headings
        if (key.indexOf('heading') !== 0) {
          return acc;
        }

        // Indent by two spaces per heading level after h1
        let indent = '';
        for (let idx = 1; idx < props.level; idx++) {
          indent = `${indent}  `;
        }

        // Append line to TOC
        // This is where you'd add a link using Markdown syntax if you wanted
        return acc.concat([`${indent}* ${props.children}`]);
      }, []);

      return (
        <div>
          <Markdown source={TOCLines.join("\n")} />
          {children}
        </div>
      );
    },

Basically it...

  1. Loops through the rendered child components of the <Markdown /> component
  2. Turns the headings back into Markdown
  3. Renders that using a nested <Markdown /> component

Seems to work!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

d0lb33 picture d0lb33  路  3Comments

LinusU picture LinusU  路  3Comments

AlexLerman picture AlexLerman  路  3Comments

ghost picture ghost  路  4Comments

joelin109 picture joelin109  路  3Comments