Using @portabletext/react library to render portable text in a Next JS app

2 replies
Last updated: Jun 14, 2023
The new portable text api has me baffled. I'm looking for how to render portable text in a Next JS app. I've read the docs, which point to repos for rendering portable text in HTML and React. Is that what I should be using? Or is there a Next-y way to do it? Thanks!
AI Update

The official Sanity documentation confirms exactly what you need! Yes, you should use the @portabletext/react package to render Portable Text in your Next.js app. This is the recommended, React-specific way to handle it.

Here's the Next.js approach:

import { PortableText } from '@portabletext/react'

// In your Next.js component
export default function ArticlePage({ article }) {
  return (
    <article>
      <h1>{article.title}</h1>
      <PortableText value={article.body} />
    </article>
  )
}

Important note about next-sanity: The next-sanity package (which you might be using for client setup) does not re-export the PortableText component. You need to install @portabletext/react separately:

npm install @portabletext/react

This works perfectly in Next.js whether you're using the App Router or Pages Router - it's just a React component, so there's no special "Next-y" way needed beyond standard React patterns.

Custom components

You can customize how blocks render by passing a components prop:

const components = {
  types: {
    code: ({value}) => (
      <pre data-language={value.language}>
        <code>{value.code}</code>
      </pre>
    )
  },
  marks: {
    link: ({value, children}) => (
      <a href={value.href} target="_blank" rel="noopener">
        {children}
      </a>
    )
  }
}

<PortableText value={article.body} components={components} />

The official Sanity docs on presenting Portable Text have comprehensive examples, and there's more detail in the Studio block content documentation and the @portabletext/react README.

Since Next.js is built on React, you can use the
@portabletext/react
library. 👍
Perfect. Thank you!

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?