how to support TOC?
wulucxy opened this issue · comments
@jamesknelson I need to support TOC heading,so do you have any plan to support TOC?
You can build a TOC by just iterating through the element returned by the Document component. Here's an example from my code for reactarmory.com:
let contentElement = MDXDocument({ ...documentProps, factories })
let previousId
let sequence = 1
let levelIds = []
let tableOfContents = new Map()
if (contentElement.props.children) {
for (let i = 0; i < contentElement.props.children.length; i++) {
let element = contentElement.props.children[i]
// Heading elements are configured to render with the DocumentHeading
// component by the document's "factories" prop.
if (element.type === DocumentHeading) {
let level = element.props.level
if (level >= minTOCHeadingLevel && level <= maxTOCHeadingLevel) {
let { id, content } = element.props
let parentIds = levelIds.slice(maxTOCHeadingLevel! - 2, level - 1)
levelIds[level - 1] = id
tableOfContents.set(id, {
id,
level,
parentIds,
previousId,
sequence,
title: content,
})
previousId = id
sequence++
}
}
}
}
I don't currently have any plans for anything more specific.