Skip to content

Instantly share code, notes, and snippets.

@kmelve
Created January 27, 2019 10:23
Show Gist options
  • Select an option

  • Save kmelve/8219fd1269a9e21e4eb25156b1d91b50 to your computer and use it in GitHub Desktop.

Select an option

Save kmelve/8219fd1269a9e21e4eb25156b1d91b50 to your computer and use it in GitHub Desktop.
A simple example of sanity.io’s Editor for Portable Text with a Table of Contents viewer
import React, { Fragment } from 'react'
import { BlockEditor } from 'part:@sanity/form-builder'
class EditorWithToC extends React.PureComponent {
generateToC = portableText => {
if (!portableText) { return [] }
const defaultHeadings = /h[1-4]/
const headings = portableText.filter(({ style }) => style.match(defaultHeadings))
return (
<Fragment>
{headings.map(({ style, _key, children }) => (
<Fragment>
<span key={_key}>
{'-'.repeat(style.replace(/[^\d]/g, ''))}{' '}
{children.map(({ text }) => text).join()}
</span><br />
</Fragment>
))}
</Fragment>
)
}
render() {
return (
<div>
<BlockEditor {...this.props} />
<details>
<summary>Table of Contents</summary>
<div><pre>{this.generateToC(this.props.value)}</pre></div>
</details>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment