How to add text alignment to Portable Text editor in Sanity?
Hey Lars! Welcome to Sanity β glad you're enjoying it so far!
You're absolutely right that Portable Text doesn't support text alignment out of the box. This is actually by design β Sanity focuses on structured content rather than visual styling, which helps keep your content portable across different platforms (web, mobile, etc.). That said, you definitely can add text alignment if you need it!
How to Add Text Alignment
You'll need to add a custom property to your block type. Here's how:
1. Add textAlign to your block schema
defineField({
name: 'content',
type: 'array',
of: [
{
type: 'block',
// Add custom properties to blocks
fields: [
{
name: 'textAlign',
type: 'string',
title: 'Text Alignment',
options: {
list: [
{title: 'Left', value: 'left'},
{title: 'Center', value: 'center'},
{title: 'Right', value: 'right'},
{title: 'Justify', value: 'justify'}
]
}
}
]
}
]
})2. Create a custom input component to show alignment in the editor
To see the alignment live in the Studio editor, you'll need a custom block renderer component. Check out the Portable Text Editor customization docs:
const AlignmentBlockEditor = (props) => {
const {value, renderDefault} = props
const alignment = value?.textAlign || 'left'
return (
<div style={{textAlign: alignment}}>
{renderDefault(props)}
</div>
)
}
// Then in your schema:
{
type: 'block',
components: {
block: AlignmentBlockEditor
},
fields: [/* your textAlign field */]
}3. Render it on your frontend
When rendering with @portabletext/react, handle the custom property:
import {PortableText} from '@portabletext/react'
const components = {
block: ({value, children}) => {
const alignment = value?.textAlign || 'left'
return (
<p style={{textAlign: alignment}}>
{children}
</p>
)
}
}
<PortableText value={content} components={components} />Important Considerations
Before you implement this, consider whether you really need alignment in your content. Many teams find it better to handle alignment through CSS/design systems rather than storing it as content data. This keeps your content more maintainable and consistent across platforms.
If you do need it, the approach above will work! The ultimate guide to customizing Portable Text has tons more examples of adding custom properties and rendering them, including how to add custom blocks, annotations, and more complex customizations.
Good luck with your project! π
Show original thread5 replies
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.