Skip to content

Instantly share code, notes, and snippets.

@paulpopus
Created July 8, 2023 16:07
Show Gist options
  • Save paulpopus/59302cf8fab8dbc05f35c8c352b5e888 to your computer and use it in GitHub Desktop.
Save paulpopus/59302cf8fab8dbc05f35c8c352b5e888 to your computer and use it in GitHub Desktop.
Payload Slate.js Rich Text Serialiser
import React, { Fragment } from 'react'
import { Text as SlateText } from 'slate'
import Link from 'next/link'
import { getSectionForCollection } from '@utilities/getSectionForCollection'
function Serialise({ content }: any) {
return (
<>
{content?.map((node: any, i: number) => {
if (!node) {
return null
}
if (SlateText.isText(node)) {
let text: string | any = String(node.text)
/* @ts-ignore */
if (node.bold) {
text = <strong key={i}>{text}</strong>
}
/* @ts-ignore */
if (node.code) {
text = <code key={i}>{text}</code>
}
return <Fragment key={i}>{text}</Fragment>
}
switch (node.type) {
case 'ul':
return (
<ul key={i}>
<Serialise content={node.children} />
</ul>
)
case 'ol':
return (
<ol key={i}>
<Serialise content={node.children} />
</ol>
)
case 'li':
return (
<li key={i}>
<Serialise content={node.children} />
</li>
)
case 'h1':
return (
<h1 key={i}>
<Serialise content={node.children} />
</h1>
)
case 'h2':
return (
<h2 key={i}>
<Serialise content={node.children} />
</h2>
)
case 'h3':
return (
<h3 key={i}>
<Serialise content={node.children} />
</h3>
)
case 'h4':
return (
<h4 key={i}>
<Serialise content={node.children} />
</h4>
)
case 'h5':
return (
<h5 key={i}>
<Serialise content={node.children} />
</h5>
)
case 'code':
return (
<code key={i}>
<Serialise content={node.children} />
</code>
)
case 'link':
if (node.linkType === 'custom') {
return (
<Link href={node.url} target={node.newTab ? '_blank' : '_self'} key={i}>
<Serialise content={node.children} />
</Link>
)
}
if (node.linkType === 'internal') {
const section = getSectionForCollection(node.doc?.relationTo)
const slug = node.doc?.value?.slug ?? ''
return (
<Link legacyBehavior={false} href={`${section}/${slug}`} target={node.newTab ? '_blank' : '_self'} key={i}>
<Serialise content={node.children} />
</Link>
)
}
return null
default:
return (
<p key={i}>
<Serialise content={node.children} />
</p>
)
}
})}
</>
)
}
interface Props {
text: any[]
}
export default function RichTextSerialiser({ text }: Props) {
if (!text) {
return null
}
return <Serialise content={text} />
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment