How to insert inline blocks (like current date/time) in Portable Text?
Yes, you can absolutely create inline objects in Portable Text! You don't need to use annotations or marks for this.
The solution is to add your custom object type to the block's of array rather than the parent array's of. This makes the object appear inline within the text, rather than as a separate block.
Here's how to create an inline "current date" block:
{
type: 'block',
of: [
{
type: 'object',
name: 'currentDate',
title: 'Current Date',
fields: [
{
name: 'format',
type: 'string',
options: {
list: ['short', 'long', 'relative']
}
}
],
// Optional: add an icon for the toolbar
icon: () => '📅',
// Optional: customize the preview
components: {
preview: {
select: {
format: 'format'
},
prepare({format}) {
return {
title: `📅 ${format || 'default'} date`
}
}
}
}
}
]
}The key difference is that objects in block.of appear inline within the text (like you can insert them mid-sentence), whereas objects in the parent array's of appear as separate block-level items.
When rendering on the frontend, you can use the Portable Text libraries to handle these inline objects. They'll have an isInline property you can check:
const components = {
types: {
currentDate: ({value, isInline}) => {
const date = new Date();
const format = value?.format || 'short';
// Format according to preference
return <span>{date.toLocaleDateString()}</span>;
}
}
}This gives you true inline objects that editors can insert anywhere in the text, and they'll dynamically display the current date/time when rendered. Much cleaner than using annotations!
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.