<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Danila Reutov on Medium]]></title>
        <description><![CDATA[Stories by Danila Reutov on Medium]]></description>
        <link>https://medium.com/@dan.reutov?source=rss-58565fa9b47------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Pp22DMd2qsQMwNphX2hrxQ.png</url>
            <title>Stories by Danila Reutov on Medium</title>
            <link>https://medium.com/@dan.reutov?source=rss-58565fa9b47------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:30:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dan.reutov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating a Text Editor in React.js]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/creating-a-text-editor-in-react-js-db006a120d85?source=rss-58565fa9b47------2</link>
            <guid isPermaLink="false">https://medium.com/p/db006a120d85</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[draftjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Danila Reutov]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 07:40:32 GMT</pubDate>
            <atom:updated>2025-04-02T07:17:17.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*Ru-mOd4RcKElwYdob_Pt7Q.png" /></figure><p>Hi! My name is Danila, and I am a front-end teamlead at <a href="https://www.lonto.io/">Lonto</a>.</p><p>Once I needed to implement a custom text editor in a project on React.js. I found this task quite interesting and decided to describe my experience. In this guide I will describe a step by step guide on creating a text editor with basic features.</p><p>I hope you’ll find it useful.</p><p>Contents:</p><ol><li>The description of the task</li><li>What is Draft.js?</li><li>Architecture</li><li>Let’s start coding</li><li>Creating simple blocks</li><li>Inline text styles</li><li>Creating interactive elements</li><li>Handling keyboard shortcuts</li><li>HTML export-import in the editor</li><li>Instead of conclusion</li></ol><h3>1. Task description</h3><p>Let’s make up some requirements for our editor. It should:</p><ol><li>Have preset element styles: headings, lists, etc.</li><li>Be able to format text: bold, italic, etc.</li><li>Support interactive elements, such as links</li><li>Support keyboard shortcuts</li><li>Be able to import/export content to HTML</li></ol><p>Browsers can handle native text events differently, so it was difficult to implement everything from scratch.</p><p>Thus, I started looking for ready-made solutions. And the most popular was Draft.js.</p><h3>2. What is Draft.js?</h3><p><a href="https://draftjs.org/">Draft.js</a> is a framework for working with text on React.js. It allows you to create an editor state that stores all information about content, cursor position, and more. It also provides cross-browser features that can conveniently change this state. Draft.js handles immutable data with <a href="https://immutable-js.com/">immutable.js</a>. This means that when the state changes, we overwrite it completely with the new version.</p><p>Content in the Draft.js editor is built from <a href="https://draftjs.org/docs/api-reference-content-block/">blocks</a>. A block is a data structure that stores information about the text within it. Each block can be given its own unique data and render settings: set the tag, styles, attributes, or just specify the React component. You can apply <a href="https://draftjs.org/docs/advanced-topics-inline-styles">inline styles</a> (e.g., bold) to any text fragment in the block. And to create more complex and interactive elements, Draft.js has <a href="https://draftjs.org/docs/advanced-topics-entities/">Entities</a> and <a href="https://draftjs.org/docs/advanced-topics-decorators/">Decorators</a>. You can use them to render custom React components and link them to text fragments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0igDBFSY_I9zPY_C" /></figure><h3>3. Architecture</h3><p>Our component will consist of several parts:</p><ol><li>Editor window</li><li>Controls</li></ol><p>We will put the entire API of our editor in useEditor — a separate React hook.</p><p>The design of the editor can be customizable, and the controls can be located separately from the editor window. To avoid props drilling when passing the editor API to components, we will use the React context. This will allow us to easily get the necessary data and functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/0*uEezyfFgO3s2OYZT" /></figure><p>Our editor’s architecture</p><h3>4. Let’s start coding</h3><p>To make things simpler, in this guide we will use the typescript template of <a href="https://create-react-app.dev/">CRA</a>.</p><pre>$ npx create-react-app editor --template typescript</pre><p>Let’s establish the necessary dependencies:</p><pre>$ yarn add draft-js draft-convert</pre><ul><li><em>draft-js</em> is a Draft.js framework</li><li><em>draft-convert</em> is a library to easily import and export data from Draft.js. We’ll have a closer look at it in the Export-import of HTML to the editor part.</li></ul><p>Let’s set the types for the libraries described above:</p><pre>$ yarn add -D @types/draft-js @types/draft-convert </pre><p>And create the <em>useEditor.tsx</em> file. It will contain the React hook, in which we will store all the logic of our editor:</p><pre>// src/TextEditor/useEditor.tsx<br>import { EditorState } from &#39;draft-js&#39;;<br>import * as React from &#39;react&#39;;<br> <br>export type EditorApi = {<br>  state: EditorState;<br>  onChange: (state: EditorState) =&gt; void;<br>}<br><br>export const useEditor = (): EditorApi =&gt; {<br>  const [state, setState] = React.useState(() =&gt; EditorState.createEmpty());<br>  <br>  return React.useMemo(() =&gt; ({<br>    state,<br>    onChange: setState<br>  }), [state])<br>}</pre><p>Now, we create an empty immutable state of our editor with the <em>EditorState.createEmpty()</em> method and store it in the local state. We will gradually add features and logic to it.</p><p>Let’s create a React Context to throw the editor’s API:</p><pre>// src/TextEditor/context.tsx<br>import * as React from &#39;react&#39;;<br>import { EditorApi, useEditor } from &#39;./useEditor&#39;;<br><br>const TextEditorContext = React.createContext&lt;EditorApi | undefined&gt;(undefined);<br><br>export const useEditorApi = () =&gt; {<br>  const context = React.useContext(TextEditorContext);<br>  if (context === undefined) {<br>    throw new Error(&#39;useEditorApi must be used within TextEditorProvider&#39;);<br>  }<br>  <br>  return context;<br>}<br><br>export const TextEditorProvider: React.FC = ({ children }) =&gt; {<br>  const editorApi = useEditor();<br>  <br>  return (<br>    &lt;TextEditorContext.Provider value={editorApi}&gt;<br>      {children}<br>    &lt;/TextEditorContext.Provider&gt;<br>  )<br>}</pre><p>Now we can access the editor functions anywhere in our app using the <em>useEditorApi</em> hook:</p><pre>const editorApi = useEditorApi();</pre><p>Let’s wrap the components with a TextEditorProvider:</p><pre>// src/App.tsx<br>function App() {<br>  return (<br>    &lt;TextEditorProvider &gt;<br>      &lt;ToolPanel /&gt;<br>      &lt;TextEditor /&gt;<br>    &lt;/TextEditorProvider&gt;<br>  );<br>}</pre><p>We’ll create the <em>TextEditor</em> window component:</p><pre>// src/TextEditor/index.ts<br>export { default } from &#39;./TextEditor&#39;;</pre><pre>// src/TextEditor/TextEditor.tsx<br>import * as React from &#39;react&#39;;<br>import { Editor } from &#39;draft-js&#39;;<br>import { useEditorApi } from &#39;./context&#39;;<br>import cn from &#39;classnames&#39;;<br>import &#39;./TextEditor.scss&#39;;<br><br>export type TextEditorProps = {<br>  className?: string;<br>}<br><br>const TextEditor: React.FC&lt;TextEditorProps&gt; = ({ className }) =&gt; {<br>  const { state, onChange } = useEditorApi();<br>  <br>  return (<br>    &lt;div className={cn(&quot;text-editor&quot;, className)}&gt;<br>      &lt;Editor<br>        placeholder=&quot;Введите ваш текст&quot;<br>        editorState={state}<br>        onChange={onChange}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default TextEditor;</pre><p>We’ve plugged in the basic <em>Editor</em> component from the <em>Draft.js</em> package. It will create the editable field and manage the content. We’ll bind it to the previously created editor’s API.</p><p>Let’s create a toolbar component:</p><pre>// src/ToolPanel/index.ts<br>export { default } from &#39;./ToolPanel&#39;;</pre><pre>// src/ToolPanel/ToolPanel.tsx<br>import * as React from &#39;react&#39;;<br>import { EditorApi } from &#39;../useEditor&#39;;<br>import &#39;./ToolPanel.scss&#39;;<br><br>const ToolPanel:React.FC&lt;ToolPanelProps&gt; = ({ className } ) =&gt; {<br>  return (<br>    &lt;div className={cn(&#39;tool-panel&#39;, className)}&gt;<br>      {/* Здесь будет код для элементов управления */}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ToolPanel;</pre><h3>5. Creating simple blocks</h3><p>We’ve created an editor, but so far it’s no different than a simple <em>textarea</em>. Let’s add the ability to create blocks.</p><p>Draft.js contains settings for basic block types by default. A complete list can be found <a href="https://draftjs.org/docs/advanced-topics-custom-block-render-map">here</a>.</p><p>Let’s create <em>config.ts </em>— a configuration file:</p><pre>// src/TextEditor/config.ts<br>export enum BlockType {<br>  /* Заголовки */<br>  h1 = &#39;header-one&#39;,<br>  h2 = &#39;header-two&#39;,<br>  h3 = &#39;header-three&#39;,<br>  h4 = &#39;header-four&#39;,<br>  h5 = &#39;header-five&#39;,<br>  h6 = &#39;header-six&#39;,<br>  /* Цитата */<br>  blockquote = &#39;blockquote&#39;,<br>  /* Блок с кодом */<br>  code = &#39;code-block&#39;,<br>  /* Список */<br>  list = &#39;unordered-list-item&#39;,<br>  /* Нумерованный список */<br>  orderList = &#39;ordered-list-item&#39;,<br>  /* Сноска */<br>  cite = &#39;cite&#39;,<br>  /* Простой текст */<br>  default = &#39;unstyled&#39;,<br>}</pre><p>We have described the enum with block type names, and added a new footnote <em>cite</em> block. But so far the editor knows nothing about how to handle new block types. To add custom blocks to Draft.js, you need to create an <a href="https://draftjs.org/docs/advanced-topics-custom-block-render-map#configuring-block-render-map">immutable block map</a>. Let’s use the <em>Immutable.Map</em> method from the <em>immutable</em> package (it is installed with Draft.js). We’ve set the name of our new block (<em>cite</em>) and specified the name of the tag with which it should appear in the DOM. To avoid describing the default blocks, let’s merge the default block map with our map using the <em>DefaultDraftBlockRenderMap.merge</em> method:</p><pre>// src/TextEditor/config.ts<br>import Immutable from &#39;immutable&#39;;<br>import { DefaultDraftBlockRenderMap } from &#39;draft-js&#39;;<br><br>...<br><br>const CUSTOM_BLOCK_RENDER_MAP = Immutable.Map({<br>  [BlockType.cite]: {<br>    element: &#39;cite&#39;, &lt;-- название тега<br>  },<br>});<br><br>export const BLOCK_RENDER_MAP = DefaultDraftBlockRenderMap.merge(CUSTOM_BLOCK_RENDER_MAP);</pre><p>Next, let’s set the editor’s new configuration:</p><pre>// src/TextEditor/TextEditor.tsx<br>import { BLOCK_RENDER_MAP } from &#39;./config&#39;;<br>...<br>&lt;Editor<br>    ...<br>    blockRenderMap={BLOCK_RENDER_MAP}<br>/&gt;</pre><p>Our editor can handle block types now. To create block type controls, we need to add two fields to the <em>useEditor</em> hook:</p><ul><li>toggleBlockType — a function for toggling the block type</li><li>currentBlockType — a variable with the value of the current block type that lets us add an active state to the element</li></ul><p>Draft.js contains the RichUtils class with auxiliary methods for text editing. To implement <em>toggleBlockType</em>, let’s use the <em>RichUtils.toggleBlockType</em> method to apply a specific block type to the current state of the editor:</p><pre>// src/TextEditor/useEditor.tsx<br>export type EditorApi = {<br>  ...<br>  toggleBlockType: (blockType: BlockType) =&gt; void;<br>}<br><br>export const useEditor = (html?: string): EditorApi =&gt; {<br>    ...<br>    const toggleBlockType = React.useCallback((blockType: BlockType) =&gt; {<br>      setState((currentState) =&gt; RichUtils.toggleBlockType(currentState, blockType))<br>    }, []);<br>    ...<br>}</pre><p>The <em>currentBlockType</em> implementation will look like this:</p><pre>// src/TextEditor/useEditor.tsx<br>import { BlockType } from &#39;./config&#39;;<br><br>export type EditorApi = {<br>  ...<br>  currentBlockType: BlockType;<br>}<br><br>export const useEditor = (html?: string): EditorApi =&gt; {<br>    ...<br>    const currentBlockType = React.useMemo(() =&gt; {<br>      /* Шаг 1 */<br>      const selection = state.getSelection();<br>      /* Шаг 2 */<br>      const content = state.getCurrentContent();<br>      /* Шаг 3 */<br>      const block = content.getBlockForKey(selection.getStartKey());<br>      /* Шаг 4 */<br>      return block.getType() as BlockType;<br>    }, [state]);<br>    ...<br>}</pre><p>Let’s take a closer look at the code.</p><p><strong>Step 1:</strong> We get the map that stores <a href="https://draftjs.org/docs/api-reference-selection-state/#internaldocs-banner">info</a> about where the user’s carriage is located.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/0*0B4hPY6oqty7JJeJ" /></figure><p>Let me remind you that Draft.js works with immutable data, so you can use the <em>toJS</em> method to see what is stored in the <em>selection</em></p><p><strong>Step 2:</strong> We get our editor’s <a href="https://draftjs.org/docs/api-reference-content-state/#internaldocs-banner">content map</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/0*7TgxfBBR6lwaqwiz" /></figure><p><strong>Step 3:</strong> We use the key field to find the current block. The key is a unique hash that Draft.js has generated.</p><p><strong>Step 4:</strong> We get the type of the found block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*Lnv262ooMFIsaVZ1DE6xjg.gif" /></figure><h3>6. Inline text styles</h3><p>Now let’s create functions to apply styles to the highlighted text.</p><p>Draft.js has built-in style types for inline styles. Let’s use them and add our own custom type. Our style will change the background and font color.</p><p>First, let’s describe the enum for inline styles in our config:</p><pre>// src/TextEditor/config.ts<br>export enum InlineStyle {<br>  BOLD = &#39;BOLD&#39;,<br>  ITALIC = &#39;ITALIC&#39;,<br>  UNDERLINE = &#39;UNDERLINE&#39;,<br>  ACCENT = &#39;ACCENT&#39; // our custom style code<br>}</pre><p>Since we have a custom style, we need to describe what styles it will apply. To do this, let’s create a map:</p><pre>// src/TextEditor/config.ts<br>export const CUSTOM_STYLE_MAP = {<br>  [InlineStyle.ACCENT]: {<br>    backgroundColor: &#39;#F7F6F3&#39;,<br>    color: &#39;#A41E68&#39;,<br>  },<br>};</pre><p>And now we need to set the map in the <em>Editor</em>:</p><pre>// src/TextEditor/TextEditor.tsx<br>&lt;Editor<br>  customStyleMap={CUSTOM_STYLE_MAP}<br>  ...<br>/&gt;</pre><p>Now the editor knows how to handle our styles. Next, we need to implement inline styles control buttons:</p><ul><li><em>toggleInlineStyle</em> is the function for toggling the inline style on or off;</li><li><em>hasInlineStyle</em> is a function that indicates whether a particular style is applied to the highlighted text.</li></ul><p>Again, we can use <em>RichUtils</em> to accomplish this task:</p><pre>// src/TextEditor/useEditor.ts<br>const toggleInlineStyle = React.useCallback((inlineStyle: InlineStyle) =&gt; {<br>  setState((currentState) =&gt; RichUtils.toggleInlineStyle(currentState, inlineStyle))<br>}, []);<br><br>const hasInlineStyle = React.useCallback((inlineStyle: InlineStyle) =&gt; {<br>  /* We get an immutable Set with style keys */<br>  const currentStyle = state.getCurrentInlineStyle();<br>  /* We check to see if the style we&#39;ve passed is there */<br>  return currentStyle.has(inlineStyle);<br>}, [state]);</pre><p>Now we can easily add inline style control buttons:</p><pre>// src/ToolPanel/ToolPanel.tsx<br>const INLINE_STYLES_CODES = Object.values(InlineStyle);<br><br>const ToolPanel: React.FC = () =&gt; {<br>  const { toggleInlineStyle, hasInlineStyle } = useEditorApi();<br>  <br>  return (<br>    &lt;div className=&quot;tool-panel&quot;&gt;<br>      ...<br>      {INLINE_STYLES_CODES.map((code) =&gt; {<br>        const onMouseDown = (e) =&gt; {<br>          e.preventDefault();<br>          toggleInlineStyle(code);<br>        };<br>    <br>        return (<br>          &lt;button<br>            key={code}<br>            className={cn(<br>              &quot;tool-panel__item&quot;,<br>              hasInlineStyle(code) &amp;&amp; &quot;tool-panel__item_active&quot;<br>            )}<br>            onMouseDown={onMouseDown}<br>          &gt;<br>            {code}<br>          &lt;/button&gt;<br>        );<br>      })}<br>    &lt;/div&gt;<br>  );<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*bQQClr4VbM3_I8qn_QHZrA.gif" /></figure><h3>7. Creating interactive elements</h3><p>Let’s look at the process of creating interactive elements using the example of inserting links. We will use <a href="https://draftjs.org/docs/api-reference-entity/#internaldocs-banner">Entities</a> for that purpose. Entity is an object that stores metadata for a specific text fragment. It has three properties:</p><ul><li>type — Entity type name</li><li>mutability — type of text binding (more on it below)</li><li>data — metadata</li></ul><p>Let’s create an <em>Entity</em> type enumeration in the config:</p><pre>// src/TextEditor/config.ts<br>export enum EntityType {<br>  link = &#39;link&#39;,<br>}</pre><p>Next, let’s create a <em>Link</em> React component which will be displayed in place of the links:</p><pre>// src/TextEditor/Link/Link.tsx<br>import { ContentState } from &#39;draft-js&#39;;<br>import * as React from &#39;react&#39;;<br><br>type LinkProps = {<br>  children: React.ReactNode;<br>  contentState: ContentState;<br>  entityKey: string;<br>}<br><br>const Link: React.FC&lt;LinkProps&gt; = ({ contentState, entityKey, children }) =&gt; {<br>  /* We get the URL using the unique Entity key */<br>  const { url } = contentState.getEntity(entityKey).getData();<br>  <br>  return (<br>    &lt;a href={url}&gt;<br>      {children}<br>    &lt;/a&gt;<br>  );<br>}<br><br>export default Link;</pre><p>Each <em>Entity</em> is assigned a unique hash key when it is created. We can use it to access the stored metadata — the <em>url</em> in this case. We will set it up when we create the Entity link.</p><p>There is a system of <a href="https://draftjs.org/docs/advanced-topics-decorators/">Decorators</a> that lets Draft.js understand which text fragment the Entity is attached to.</p><p>The decorator consists of three parts:</p><ul><li><em>strategy</em> is the function that searches the text fragment in the place of which you want to display a component</li><li><em>component</em> is a component you want to display</li><li>props are props to be passed to the component</li></ul><p>Let’s create a decorator to bind links:</p><pre>// src/TextEditor/Link/index.ts<br>import Link from &quot;./Link&quot;;<br>import { EntityType } from &quot;../config&quot;;<br>import { ContentBlock, ContentState, DraftDecorator } from &quot;draft-js&quot;;<br><br>function findLinkEntities(<br>  /* The block in which the last change was made */<br>  contentBlock: ContentBlock,<br>  /* A function to be called with text fragment indexes */<br>  callback: (start: number, end: number) =&gt; void,<br>  /* Current content map */<br>  contentState: ContentState<br>): void {<br>  /* We perform the filter function for each character in the block */<br>  contentBlock.findEntityRanges((character) =&gt; {<br>    /* We get the Entity key */<br>    const entityKey = character.getEntity();<br>    /* We check that Entity belongs to the Entity link type */<br>    return (<br>      entityKey !== null &amp;&amp;<br>      contentState.getEntity(entityKey).getType() === EntityType.link<br>    );<br>  }, callback);<br>}<br><br>const decorator: DraftDecorator = {<br>  strategy: findLinkEntities,<br>  component: Link,<br>};<br><br>export default decorator;</pre><p>Now we can connect the created decorator to our editor:</p><pre>// src/TextEditor/useEditor.tsx<br>import { CompositeDecorator } from &#39;draft-js&#39;;<br>import LinkDecorator from &#39;./Link&#39;;<br><br>/* We combine the decorators into one */<br>const decorator = new CompositeDecorator([LinkDecorator]);<br><br>export const useEditor = (): EditorApi =&gt; {<br>    const [state, setState] = React.useState(() =&gt; EditorState.createEmpty(decorator));<br>    ...</pre><p>Great! Now our editor can handle links. Let’s tell it how to add and edit them.</p><p>Since there can be several Entity types in the editor, let’s create a common function to add an <em>Entity</em>. It will only be available inside the hook and won’t be available in components. To add a link type, let’s create a separate addLink function. It will be available in the editor’s API:</p><pre>// src/TextEditor/useEditor.tsx<br>import { EditorState, RichUtils } from &#39;draft-js&#39;;<br><br>export const useEditor = (): EditorApi =&gt; {<br>    ...<br>    const addEntity = React.useCallback((entityType: EntityType, data: Record&lt;string, string&gt;, mutability: DraftEntityMutability) =&gt; {<br>     setState((currentState) =&gt; {<br>        /* We retrieve the current content */<br>       const contentState = currentState.getCurrentContent();<br>        /* We create an Entity with data */<br>       const contentStateWithEntity = contentState.createEntity(entityType, mutability, data);<br>        /* We get a unique Entity key */<br>       const entityKey = contentStateWithEntity.getLastCreatedEntityKey();<br>        /* We combine the current state with the new one */<br>       const newState = EditorState.set(currentState, { currentContent: contentStateWithEntity });<br>       /* We insert the link to the specified place */<br>        return RichUtils.toggleLink(newState, newState.getSelection(), entityKey);<br>    })<br>  }, []);<br><br>  const addLink = React.useCallback((url) =&gt; {<br>  addEntity(EntityType.link, { url }, &#39;MUTABLE&#39;)<br>  }, [addEntity]);<br> <br> return {<br>    ...<br>    addLink<br> }<br>}</pre><p><em>Entity</em> has three text binding modes:</p><ol><li><em>MUTABLE</em>: the text can be changed</li><li><em>IMMUTABLE</em>: if you change the text, the <em>Entity</em> will be deleted</li><li><em>SEGMENTED</em>: it works in the same way as <em>IMMUTABLE</em> with the only difference that if you delete a character from the text consisting of several words, the word will be removed, but the remaining words will remain bound to the <em>Entity</em>. (Example: “Katy wa|shed the dishes” → [backspace] → “Katy the dishes”)</li></ol><p>We’ve chosen the <em>MUTABLE</em> mode because the link text can be editable.</p><p>We can implement the ‘Add a link’ button easily now. To specify the address of the link, let’s use the <em>prompt</em>:</p><pre>// src/ToolPanel/ToolPanel.tsx<br>const ToolPanel: React.FC = () =&gt; {<br>  const { addLink } = useEditorApi();<br><br>  const handlerAddLink = () =&gt; {<br>   const url = prompt(&#39;URL:&#39;);<br><br>    if (url) {<br>      addLink(url);<br>    }<br>  }<br><br> return (<br>    ...<br>    &lt;button onClick={handlerAddLink}&gt;<br>     Add a link<br>    &lt;/button&gt;<br>    ...<br> );<br>}</pre><p>Links are added. Let’s refine the editor so you can edit the <em>URL</em> of an already created link.</p><p>To simplify the example, let’s make it so that when you click on the link in the editor, the <em>prompt</em> with the pre-filled <em>url</em> appears again.</p><p>Let’s process the click in the component:</p><pre>// src/TextEditor/Link/Link.tsx<br>import { useEditorApi } from &#39;../context&#39;;<br><br>const Link: React.FC&lt;LinkProps&gt; = ({ contentState, entityKey, children }) =&gt; {<br>  const { setEntityData } = useEditorApi();<br>  const { url} = contentState.getEntity(entityKey).getData();<br>  <br>  const handlerClick = () =&gt; {<br>    const newUrl = prompt(&#39;URL:&#39;, url);<br>    if (newUrl) {<br>      setEntityData(entityKey, { url: newUrl });<br>    }<br>  }<br>  <br>  return (<br>    &lt;a href={url} onClick={handlerClick}&gt;<br>      {children}<br>    &lt;/a&gt;<br>  );<br>}</pre><p>And let’s create a function to overwrite the <em>Entity</em> data:</p><pre>// src/TextEditor/useEditor.tsx<br>export const useEditor = (): EditorApi =&gt; {<br>    ...<br>    const setEntityData = React.useCallback((entityKey, data) =&gt; {<br>    setState((currentState) =&gt; {<br>      /* We retrieve the current content */<br>      const content = currentState.getCurrentContent();<br>      /* Let&#39;s combine the current Entity data with the new data */<br>      const contentStateUpdated = content.mergeEntityData(<br>        entityKey,<br>        data,<br>      )<br>      /* We update the state of the editor, indicating the type of change */<br>      return EditorState.push(currentState, contentStateUpdated, &#39;apply-entity&#39;);<br>    })<br>  }, []);<br><br>  export {<br>    ...<br>    setEntityData<br> }<br>}</pre><p>There are <a href="https://draftjs.org/docs/api-reference-editor-change-type/">several types</a> of editor state changes. And we need each of them so that Draft.js could correctly determine how a change affects certain functions. For example, redo and undo.</p><p>That’s it. Now we can easily add and edit custom <em>Entities</em> in our editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*e4nyBZqQxwzV-79YK4g_NQ.gif" /></figure><h3>8. Handling keyboard shortcuts</h3><p>Many text editors let you edit content using keyboard shortcuts. Draft.js has a mechanism for implementing such a behavior. The shortcut must perform a specific action — a command. Let’s create a function to handle these commands.</p><pre>// src/TextEditor/useEditor.tsx<br>export const useEditor = (): EditorApi =&gt; {<br> ...<br>  const handleKeyCommand = React.useCallback((command: DraftEditorCommand, editorState: EditorState) =&gt; {<br>   const newState = RichUtils.handleKeyCommand(editorState, command);<br><br>    if (newState) {<br>    setState(newState);<br>    return &#39;handled&#39;;<br>  }<br><br>  return &#39;not-handled&#39;;<br>  }, []);<br><br>  export {<br>    ...<br>    handleKeyCommand <br> }<br>}</pre><p>The function takes the name of the command and the current state of the editor as input, and it should return one of the two values:</p><ul><li><em>handled</em> — command applied</li><li><em>not-handled</em> — command not applied</li></ul><p>You should always try to work with the latest version to avoid the race of state updates. You can read more about that <a href="https://draftjs.org/docs/advanced-topics-editorstate-race-conditions/">here</a>.</p><p>Let’s add the handling of standard keyboard shortcuts with <em>RichUtils.handleKeyCommand</em>. For example, <em>ctrl + I</em> or <em>cmd + I</em> to apply a previously created <em>ITALIC</em> style.</p><p>Next, we need to throw our function into the Editor component:</p><pre>// src/TextEditor/TextEditor.tsx<br>&lt;Editor<br>  handleKeyCommand={editorApi.handleKeyCommand}<br>  ...<br>/&gt;</pre><p>Great, now we can handle standard keyboard shortcuts. But we’ll go further and add our own combination for our <em>ACCENT</em> custom text style. First, let’s extend the type of standard commands so that the ts doesn’t swear at us:</p><pre>// src/TextEditor/config.ts<br>import { DraftEditorCommand} from &#39;draft-js&#39;;<br><br>export type KeyCommand = DraftEditorCommand | &#39;accent&#39;; // a custom command</pre><p>Next, let’s create a function to handle key presses:</p><pre>// src/TextEditor/useEditor.tsx<br>import { KeyBindingUtil, getDefaultKeyBinding } from &#39;draft-js&#39;;<br><br>export const useEditor = (): EditorApi =&gt; {<br> ...<br>  const handlerKeyBinding = React.useCallback((e: React.KeyboardEvent) =&gt; {<br>   /* We check if the q + ctrl/cmd key is pressed */<br>    if (e.keyCode === 81 &amp;&amp; KeyBindingUtil.hasCommandModifier(e)) {<br>     return &#39;accent&#39;;<br>    }<br>   <br>    return getDefaultKeyBinding(e);<br>}, []);<br><br>return {<br>    ...<br>    handlerKeyBinding <br> }<br>}</pre><p>Note that we use the <em>getDefaultKeyBinding</em> function. It contains the logic for the standard keyboard shortcuts. We also use the <em>KeyBindingUtil.hasCommandModifier</em> utility to detect when the user presses a command key: ctrl or cmd. So, when you press <em>q + ctrl</em> or <em>q + cmd</em> the <em>accent</em> command will be executed. Now you need to handle it in <em>handleKeyCommand</em>:</p><pre>// src/TextEditor/useEditor.tsx<br>const handleKeyCommand = React.useCallback((command: DraftEditorCommand, editorState: EditorState) =&gt; {<br>   if (command === &#39;accent&#39;) {<br>    toggleInlineStyle(InlineStyle.ACCENT);<br>    return &#39;handled&#39;;<br>  }<br>  ...<br>}, []);</pre><p>This way we can add custom keyboard shortcuts.</p><h3>9. HTML export-import in the editor</h3><p>The ability to export and import data is an essential part of a text editor. Draft.js has a <a href="https://draftjs.org/docs/api-reference-data-conversion/#converttoraw">convertToRaw</a> function that allows you to load a JSON with data about all the content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/0*nPlQnsAIR7XRxSbR" /></figure><p>From this data, you can generate HTML. Having browsed the web and the npm, I found several packages that allowed me to specify in detail how to convert content to and from HTML. After weighing the pros and cons, I settled on the <a href="https://github.com/HubSpot/draft-convert"><em>draft-convert</em></a> package<em> (which we installed during the project set-up)</em> because it allowed me to conveniently implement the desired features.</p><p>Let’s create a <em>convert.tsx</em> file. In it, we will declare the functions for converting the editor’s state to HTML and back.</p><p>Let’s create a function to convert the editor’s state to HTML. In it, we will describe the rules by which we want to convert the editor’s data into layout:</p><pre>// src/TextEditor/convert.tsx<br>import { CUSTOM_STYLE_MAP, BlockType, EntityType, InlineStyle } from &#39;./config&#39;;<br><br>export const stateToHTML = convertToHTML&lt;InlineStyle, BlockType&gt;({<br>  styleToHTML: (style) =&gt; {<br>    switch (style) {<br>      case InlineStyle.BOLD:<br>        return &lt;strong /&gt;;<br>      ...<br>      case InlineStyle.ACCENT:<br>        return &lt;span className=&quot;accent&quot; style={CUSTOM_STYLE_MAP[InlineStyle.ACCENT]} /&gt;;<br>      default:<br>        return null;<br>    }<br>  },<br>  blockToHTML: (block) =&gt; {<br>    switch (block.type) {<br>      case BlockType.h1:<br>          return &lt;h1 /&gt;;<br>        ...<br>      case BlockType.default:<br>        return &lt;p /&gt;;<br>      default:<br>        return null;<br>    }<br>  },<br>  entityToHTML: (entity, originalText) =&gt; {<br>    if (entity.type === EntityType.link) {<br>      return (<br>        &lt;a href={entity.data.url}&gt;<br>          {originalText}<br>        &lt;/a&gt;<br>      );<br>    }<br>    return originalText;<br>  },<br>});</pre><p>To use our converter, let’s create a <em>toHtml</em> function:</p><pre>// src/TextEditor/useEditor.tsx<br>export const useEditor = (): EditorApi =&gt; {<br> ...<br>  const toHtml = React.useCallback(() =&gt; {<br>   return stateToHTML(state.getCurrentContent());<br>  }, [state]);<br><br>  return {<br>    ...<br>    toHtml <br> }<br>}</pre><p>And for example, let’s add a button that will output the generated HTML to the console:</p><pre>&lt;button onClick={toHtml}&gt;Print&lt;/button&gt;</pre><p>Great, now we can export the HTML from our editor. Now let’s add the ability to import the original content. Let’s describe the rules for converting HTML into the editor data:</p><pre>// src/TextEditor/convert.tsx<br>export const HTMLtoState = convertFromHTML&lt;DOMStringMap, BlockType&gt;({<br>  htmlToStyle: (nodeName, node, currentStyle) =&gt; {<br>    if (nodeName === &#39;strong&#39;) {<br>        return currentStyle.add(InlineStyle.BOLD);<br>    }<br>    ...<br>    if (nodeName === &#39;span&#39; &amp;&amp; node.classList.contains(&#39;accent&#39;)) {<br>      return currentStyle.add(InlineStyle.ACCENT);<br>    }<br><br>    return currentStyle;<br>  },<br>  htmlToBlock(nodeName, node) {<br>    switch (nodeName) {<br>      case &#39;h1&#39;:<br>        return BlockType.h1;<br>      ...<br>      case &#39;div&#39;:<br>      case &#39;p&#39;:<br>        return BlockType.default;<br>      default:<br>        return null;<br>    }<br>  },<br>  htmlToEntity: (nodeName, node, createEntity) =&gt; {<br>    if (nodeName === &#39;a&#39; &amp;&amp; node.href) {<br>      return createEntity(EntityType.link, &#39;MUTABLE&#39;, { url: node.href });<br>    }<br><br>    return undefined;<br><br>  },<br>});</pre><p>Now let’s connect the HTML converter to the editor. To do this, let’s use the standard <em>EditorState.createWithContent</em> method and refine the <em>EditorApi</em>:</p><pre>// src/TextEditor/useEditor.tsx<br>...<br>export const useEditor = (html?: string): EditorApi =&gt; {<br>  const [state, setState] = React.useState(() =&gt;<br>    html<br>      ? EditorState.createWithContent(HTMLtoState(html), decorator)<br>      : EditorState.createEmpty(decorator)<br>  );<br>  ...<br>}</pre><p>Now all we have to do is to pass the HTML! Our editor knows how to load with preset content.</p><h3>10. Instead of conclusion</h3><p>Progress does not stand still: more and more sophisticated APIs and libraries appear every day. In this article I tried to show how I solved this task a while ago. However, in my case, Mobx was connected to the project, and all the features of the useEditor hook were implemented as a class. But since the task is quite extensive, I decided not to overload the article with data and use the standard and well-known React.js hooks.</p><p>You can find the full code from the article <a href="https://github.com/ktsstudio/editor-react">here</a>.</p><p>If you have solved similar problems too, you are welcome to share your experience in the comments. What tools did you use?</p><p>Thank you for your attention!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db006a120d85" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/creating-a-text-editor-in-react-js-db006a120d85">Creating a Text Editor in React.js</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>