Lexical Tools
Learn how to use Lexical tools to manipulate Lexical state.
This feature is available since Webiny v5.38.0.
- how to parse HTML to Lexical state
- how to convert Lexical state to HTML
Overview
Webiny uses the Lexical 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
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 DOMParser 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 JSDOM, to parse your HTML to a DOM document.
Browser Usage
In the browser environment, you can simply use the DOMParser
class.
Node.js Usage
In the Node.js environment, first install a DOM library of choice. We’ll use JSDOM:
Then use it to parse your HTML, and get a DOM document:
Convert DOM to Lexical State
Once you have your DOM document, you can convert it to Lexical state:
Custom Nodes
You can configure your Lexical parser with custom Lexical nodes. This will often be necessary if your HTML contains tags unknown to Webiny.
Custom Node Mapper
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: