Created
January 27, 2019 10:23
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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