How to render a table from Sanity using portabletext/react.
To render a table from Sanity using @portabletext/react, you'll need to use the sanity-plugin-table plugin to create tables in your Sanity Studio, then create a custom component to render them in React.
Important Note
⚠️ The sanity-plugin-table only works with Studio v2, which is deprecated. You should migrate to Studio v3 when possible. The plugin has a significant limitation: table cells only support plain strings, not rich text.
Setup Process
1. Install the Plugin (Studio v2)
# Using yarn
yarn add sanity-plugin-table@studio-v2
# Or using Sanity CLI
sanity install table2. Add Table to Your Schema
In your schema, add the table type to your block content array:
{
name: "body",
title: "Body",
type: "array",
of: [
{
type: "block",
},
{
type: "table", // Add this
},
],
}3. Create a Custom Serializer for React
When rendering with @portabletext/react, you need to define a custom component for the table type:
import { PortableText } from '@portabletext/react'
const components = {
types: {
table: ({ value }) => {
const { rows } = value
return (
<table>
<tbody>
{rows.map((row, rowIndex) => (
<tr key={rowIndex}>
{row.cells.map((cell, cellIndex) => (
<td key={cellIndex}>{cell}</td>
))}
</tr>
))}
</tbody>
</table>
)
}
}
}
// Use it in your component
<PortableText value={content} components={components} />Alternative Approach
Given the limitations of the table plugin, many developers prefer creating arrays of objects to represent tabular data, then handling the table rendering on the frontend. This approach gives you more flexibility and allows for complex data structures within cells.
For more details on custom serializers and rendering Portable Text, check out the Presenting Portable Text guide in the Sanity documentation.
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.