Can I use this?

This feature is available since Webiny v5.38.0.

What you’ll learn
  • how to parse HTML to Lexical state
  • how to convert Lexical state to HTML

Overview
anchor

Webiny uses the Lexicalexternal link text editor framework to power its Rich Text Editor components. It’s very powerful, and enables us to build a feature rich and extendable text editors. The downside is that the output of the editor is not HTML, as you would expect from a WYSIWYG editor.

To help you convert Lexical’s native state shape into HTML, and vice-versa, we’ve created a set of utilities, which reside in our @webiny/lexical-converter package.

This article demonstrates how to use this utility package to convert your HTML or Lexical data into the desired form.

HTML to Lexical
anchor

To parse HTML to a valid Lexical state, Lexical editor requires a DOM document. Every environment is different, so there’s an extra step you need to take before you use our tool, and that is converting your HTML to a DOM document.

Browsers have a native DOMParserexternal link class you can just instantiate and parse your HTML.

Node.js is a bit more involved, because DOM is not a native thing for Node.js. You’ll need to use a library like JSDOMexternal link, to parse your HTML to a DOM document.

Browser Usage
anchor

In the browser environment, you can simply use the DOMParser class.

Parse HTML to a DOM document in the browser

Node.js Usage
anchor

In the Node.js environment, first install a DOM library of choice. We’ll use JSDOM:

Install JSDOM

Then use it to parse your HTML, and get a DOM document:

Parse HTML to a DOM document in Node.js

Convert DOM to Lexical State
anchor

Once you have your DOM document, you can convert it to Lexical state:

Convert DOM to Lexical State

Custom Nodes
anchor

You can configure your Lexical parser with custom Lexical nodesexternal link. This will often be necessary if your HTML contains tags unknown to Webiny.

Add Custom Nodes

Custom Node Mapper
anchor

You might also need to perform some actions on your node instance, after the DOM is parsed into a Lexical state. To process each parsed node, configure the parser with a nodeMapper property:

Add a Custom Node Mapper