Implementing Draft.js and converting rich text to Sanity portable text
Yes, you can absolutely implement Draft.js as a rich text editor on your frontend and send the data to Sanity! The key is converting Draft.js content to Portable Text, which is Sanity's structured content format.
Here's the general approach:
The Conversion Process
Since Draft.js doesn't directly output Portable Text, you'll need to convert it through HTML as an intermediate format:
- Export Draft.js to HTML - Use the
draft-js-export-htmllibrary to convert your Draft.js content state to HTML - Convert HTML to Portable Text - Use Sanity's
@sanity/block-toolspackage, specifically thehtmlToBlocksfunction
Basic Implementation
import { stateToHTML } from 'draft-js-export-html';
import { htmlToBlocks } from '@sanity/block-tools';
import { Schema } from '@sanity/schema';
// Get your Draft.js content state
const contentState = editorState.getCurrentContent();
// Convert to HTML
const html = stateToHTML(contentState);
// Define your Sanity schema (you'll need your actual block content schema)
const defaultSchema = Schema.compile({
name: 'myBlog',
types: [
/* your schema types */
]
});
const blockContentType = defaultSchema
.get('blockContent')
.jsonType;
// Convert HTML to Portable Text blocks
const blocks = htmlToBlocks(html, blockContentType, {
parseHtml: html => new DOMParser().parseFromString(html, 'text/html')
});Custom Deserialization Rules
If you have custom formatting or blocks in Draft.js, you can define custom deserialization rules when converting HTML to blocks. This lets you handle special elements like custom inline styles, embedded media, or other Draft.js decorators.
Alternative Approach
If you're building a new project, consider whether you really need Draft.js. Sanity Studio comes with its own excellent Portable Text editor that you can configure extensively to support custom blocks, decorators, and behaviors. This eliminates the conversion step entirely.
However, if you need Draft.js for specific frontend requirements (like a public-facing comment system or a custom editing experience), the HTML-to-Portable-Text conversion approach works well!
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.