portabletext/react-portabletext

Anchored Headings for Portable Text

58bits opened this issue ยท 2 comments

Wondering how we would do something similar to this...

https://www.sanity.io/schemas/anchored-headings-for-portable-text-a6c70b6e - created by @kmelve

I think I understand how to create the new block definitions for h1, h2 etc..., or a complete handler like in the example above, but in the code below, I don't believe node is available from props? And I'm not sure what to return instead of return PortableText.defaultSerializers.types.block(props) (since defaultSerializers is no longer on PortableText)

const components: PortableTextComponents = {
  block: props => {
    const { node, children } = props
    const { style, _key } = node

    if (/^h\d/.test(style)) {
      const HeadingTag = style
      // Even though HTML5 allows id to start with a digit, we append it with a letter to avoid various JS methods to act up and make problems
      const headingId = `h${_key}`
      return (
        <HeadingTag id={headingId}>
          <a href={`#${headingId}`} aria-hidden="true" tabIndex={-1}>
            #
          </a>
          <span>{children}</span>
        </HeadingTag>
      )
    }
    // ... you can put in other overrides here

    // or return the default ones ๐Ÿ‘‡
    return PortableText.defaultSerializers.types.block(props)
  }
}

Any thoughts or suggestions greatly appreciated.

Ah okay I've just ready the migration docs here...

https://github.com/portabletext/react-portabletext/blob/main/MIGRATING.md

and so...

 const { node, children } = props
 const { style, _key } = node

becomes...

 const { value, children } = props
 const { style, _key } = value

What about the return defaultSerializers? (or the 'components') equivalent?

In case anyone else finds this helpful - here's how I did this in the end.... creating a url-safe kebab-case ID for the heading element and anchor ref using slugify and a helper function to extract the text from the heading element.

import * as React from 'react'
import { PortableText } from '@portabletext/react'
import slugify from 'slugify'

const getTextFromChildren = (children: React.ReactNode) => {
  let text = ''
  React.Children.map(children, child => {
    if (typeof child === 'string') {
      text += child
    }
  })
  return text
}

type HeadingWithAnchorProps = {
  heading: string
  children: React.ReactNode
}

function HeadingWithAnchor({ heading, children }: HeadingWithAnchorProps) {
  const text = getTextFromChildren(children)
  const headingId = slugify(text, { lower: true })
  const Element = heading as keyof JSX.IntrinsicElements
  return (
    <Element id={headingId}>
      <a href={`#${headingId}`} aria-hidden="true" tabIndex={-1}>
        #
      </a>
      <span>{children}</span>
    </Element>
  )
}

const components: PortableTextComponents = {
  block: {
    h2: ({ children }) => {
      return <HeadingWithAnchor heading="h2">{children}</HeadingWithAnchor>
    },
    h3: ({ children }) => {
      return <HeadingWithAnchor heading="h3">{children}</HeadingWithAnchor>
    },
    h4: ({ children }) => {
      return <HeadingWithAnchor heading="h4">{children}</HeadingWithAnchor>
    },
  }
}