How to prevent @sanity/block-content-to-html from wrapping output in a div?

5 replies
Last updated: Apr 30, 2021
Hey folks! Using
@sanity/block-content-to-html
and wondering how I can stop the output being wrapped in a div?
AI Update

Good question! By default, when you pass multiple blocks to @sanity/block-content-to-html, it wraps the output in a container div. However, there are a couple of ways to handle this:

The Single Block Approach

The simplest solution: if you only pass a single block, the container div is automatically skipped. So if your content is just one block, you won't get the wrapper at all.

Using the className Option

According to the official documentation, when more than one block is given, a container node is created. You can pass a className option to customize it:

const html = blocksToHtml({
  blocks: content,
  className: 'my-custom-class'
})

However, this doesn't remove the container - it just lets you style it.

Custom Container Serializer

Unfortunately, @sanity/block-content-to-html doesn't have a built-in serializers.container option to completely remove or customize the wrapper element. The React version (@sanity/block-content-to-react) had a serializers.container option, but the HTML version doesn't expose this.

Consider Migrating

Important note: This package is deprecated! The README explicitly states:

⚠️ Note: This package is deprecated. We recommend migrating to its modernized successor, @portabletext/to-html.

The newer @portabletext/to-html package likely has better options for controlling the output structure and is actively maintained. If you're starting a new project or can migrate, I'd strongly recommend using that instead.

Workaround

If you're stuck with @sanity/block-content-to-html and need to remove the wrapper, you could:

  1. Process the blocks individually and concatenate the results
  2. Use string manipulation to strip the outer div from the HTML output (not ideal, but functional)
  3. Migrate to @portabletext/to-html which gives you more control over serialization

Hope this helps!

Show original thread
5 replies
I’m not sure you can, unless I’m misreading the
className
details here .
To be honest I could probably deal if I could set the class(es) of the parent
Looks like to can set container: 'div' on the serializer, but probably won't work with a fragment.
I’m still struggling to get it, sorry.
I got it. To this:
const params = { blocks: value, serializers}
I added
{ className: 'my-class-here' }

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?