Presenting Portable Text

When you query your Sanity project’s API your rich text content is returned as Portable Text. If you are accustomed to traditional or other headless CMS you are probably used to dealing with HTML or Markdown right of the box. Portable Text is designed for being used in pretty much any format or markup where you want to render rich text content.

You render Portable Text by serializing the arrays with your content into the format you need it in. There is tooling for generic markup and programming languages, and for popular frameworks, that makes it easier to serialize Portable Text and lets you decide how custom content types should be dealt with.

Plain text serialization

Serializing Portable Text to plain text can be useful when you need it previews or similar. It also helps demystify what goes into serializing Portable Text. Here's a function written in JavaScript that takes a Portable Text array as an argument, and returns it as paragraphs in plain text:

Rendering Portable Text in React

A common use case is to render rich text content from Sanity in the popular web framework React. We have made tooling that deals with the defaults out of the box, and lets you add serializers for controlling how custom content type should be rendered in the frontend. Let's look at a simple example for how to set it up:

Serialization tooling

We have helpers for this for different languages and platforms.

Pro-tip

You may notice some mentions of block text, including in the tool names. This was the nomenclature we used before open sourcing and publishing the specification for Portable Text. You can explore the specification on www.portabletext.org.

Portable Text in .NET

Portable Text in PHP

Need to serialize to something not listed here in a language we don't cover? Create an issue on the repo for Portable Text, or join us on Slack and let us know.

Deserialization

If you need to convert existing markup to Portable Text you can the JavaScript library Sanity Block Tools. You can use it both in a browser and in a node.js environment. It also lets you make custom rules to deserialize parts of your HTML into custom content types etc.

Complete example of deserialization of HTML into Portable Text blocks in a browser environment: