Join us live Sept. 27 – How Sanity and Vercel powered Morning Brew's transformation –>

How to turn PortableText into plain text in Javascript?

2 replies
Last updated: Dec 7, 2020

Hi! Is there a quick and dirty way to turn PortableText into plain text in JS? I have text for a Gatsby page that’s being transformed by “

user U
/block-content-to-react” which works really well; but it would be nice to just have a plain-text version of the page content that I could put in my meta descriptions. I’m guessing that someone must have solved this before more elegantly than I would? Thanks!

Dec 7, 2020, 1:58 AM

Hey Dan, you might find this useful, credit goes to Sanity team because I just pinched it from the portableText documentation, I use all the time for previews:

export default function toPlainText(blocks = []) {
  return blocks
    .map(block => {
      if (block._type !== 'block' || !block.children) {
        return ''
      return => child.text).join('')

Dec 7, 2020, 7:53 AM

This works perfectly. Thanks.

Dec 7, 2020, 9:06 AM Get the most out of your content is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Free to get started, pay-as-you-go on all plans.