TinyMCE React Component

repository·main·Indexed 21 days ago

https://github.com/tinymce/tinymce-react

Official React wrapper for the TinyMCE editor, providing an Editor component to integrate rich text editing into React applications. It supports both controlled and uncontrolled modes, iframe and inline rendering, and provides comprehensive props for configuration (init, plugins, toolbar) and a wide range of lifecycle and interaction event handlers.

Tokens
2.5K
Snippets
6
Records
10
Agent score
76%

What's inside @tinymce/tinymce-react

  1. Overview of @tinymce/tinymce-react

    main
    The @tinymce/tinymce-react package is an official thin wrapper around the TinyMCE editor designed to simplify its integration into React applications. It provides a React component that manages the lifecycle of the TinyMCE editor instance within a React component tree.
  2. Use the Editor component

    main

    The Editor component is the primary way to integrate TinyMCE into a React application. It supports both iframe and inline modes and can be used as a controlled or uncontrolled component.

    Key Props

    • apiKey: Required for deployments using Tiny Cloud.
    • id: A unique ID for the editor element.
    • inline: Boolean indicating if the editor should be rendered inline (on a div or other element) instead of in an iframe.
    • initialValue: The initial HTML content. Important: Do not update this prop via onEditorChange if you want to use it for controlled state, as it can make the editor unusable.
    • value: The current HTML content. Use this for controlled components.
    • onEditorChange: Callback function triggered when content changes. Receives (content: string, editor: TinyMCEEditor).
    • init: An object containing additional TinyMCE configuration options.
    • plugins & toolbar: High-level props to configure plugins and the toolbar, which override or merge with the init object.
    • tinymceScriptSrc: The URL(s) to the TinyMCE script for lazy loading. Can be a string, an array of strings, or an array of ScriptItem objects.
    • licenseKey: Tiny Cloud License Key for self-hosting.

    Controlled vs Uncontrolled

    • Uncontrolled: Provide initialValue and use onEditorChange to react to changes. Do not provide the value prop.
    • Controlled: Provide the value prop and update it via onEditorChange. The component manages the synchronization between the React state and the TinyMCE instance.
    import { Editor } from '@tinymce/tinymce-react';
    
    // Example: Controlled Component
    function MyEditor() {
      const [content, setContent] = React.useState('<p>Hello World</p>');
    
      return (
        <Editor
          apiKey='your-api-key'
          id='my-editor'
          value={content}
          onEditorChange={(newContent) => setContent(newContent)}
          init={{
            plugins: 'advlist autolink lists link image powerpaste',
            toolbar: 'undo redo | formatselect | bold italic',
          }}
        />
      );
    }
  3. Configure the Editor via the `init` prop

    main

    The init prop accepts an object of TinyMCE configuration options. However, certain keys are handled internally by the React component to ensure proper integration and should not be passed directly in init:

    • selector: Handled internally.
    • target: Handled internally.
    • readonly: Overridden by the readonly prop.
    • disabled: Overridden by the disabled prop.
    • license_key: Use the licenseKey prop instead.

    Other standard TinyMCE options can be passed freely. The component also provides top-level props for plugins and toolbar which are merged with the init configuration.

  4. Define event handlers for TinyMCE React

    main

    When providing event handlers to the TinyMCE React component, you can use the EventHandler<A> type. An event handler is a function that receives two arguments:

    1. a: An EditorEvent<A> object containing the event data.
    2. editor: The TinyMCEEditor instance.

    This type ensures that your callback functions are correctly typed according to the specific event being triggered.

    import type { EventHandler } from '@tinymce/tinymce-react';
    // Note: The exact import path depends on how the package exports these types.
    
    const myHandler: EventHandler<string> = (event, editor) => {
      console.log('Event data:', event);
      console.log('Editor instance:', editor);
    };
  5. Handle TinyMCE Editor events

    main

    The Editor component supports a wide range of event callbacks to hook into the editor's lifecycle and user interactions. Common event categories include:

    • Lifecycle Events: onInit, onRemove, onShow, onHide.
    • Content Events: onChange, onGetContent, onSetContent, onSaveContent, onLoadContent.
    • User Interaction: onClick, onFocus, onBlur, onKeyDown, onKeyUp, onMouseDown, onMouseUp, onPaste, onCopy, onCut.
    • Selection & State: onSelectionChange, onDirty, onUndo, onRedo.
    • Error Handling: onSkinLoadError, onThemeLoadError, onModelLoadError, onPluginLoadError, onIconsLoadError, onLanguageLoadError, onScriptsLoadError.

    All event props are passed as functions.

    <Editor
      onInit={(event, editor) => console.log('Editor initialized', editor)}
      onEditorChange={(content) => console.log('Content changed:', content)}
      onFocus={() => console.log('Editor focused')}
      onBlur={() => console.log('Editor blurred')}
    />
  6. Configure the TinyMCE Editor component props

    main

    The Editor component accepts several configuration props to control its behavior, appearance, and integration. Key props include:

    • apiKey: String for TinyMCE Cloud authentication.
    • licenseKey: String for license validation.
    • id: Unique identifier for the editor instance.
    • inline: Boolean to determine if the editor should be inline or a modal.
    • init: An object containing TinyMCE configuration settings.
    • initialValue: The initial content string for the editor.
    • value: The controlled value of the editor.
    • onEditorChange: Callback function triggered when the editor content changes.
    • plugins: A string or array of plugin names to load.
    • toolbar: A string or array defining the toolbar buttons.
    • disabled: Boolean to disable the editor.
    • readonly: Boolean to make the editor read-only.
    • tinymceScriptSrc: Specifies the source of the TinyMCE script. Can be a string, an array of strings, or an array of objects specifying src, async, and defer.
    <Editor
      apiKey="your-api-key"
      init={{
        plugins: 'advlist autolink lists link image',
        toolbar: 'undo redo | bold italic'
      }}
      onEditorChange={(e, editor) => console.log(e)}
    />
  7. Configure script loading for TinyMCE

    main

    You can control how the TinyMCE script is loaded using the tinymceScriptSrc and scriptLoading props.

    • tinymceScriptSrc: Can be a string, string[], or ScriptItem[]. This allows for hybrid loading modes.
    • scriptLoading: An object to configure script attributes:
      • async: Whether to add the async attribute.
      • defer: Whether to add the defer attribute.
      • delay: Number of milliseconds to wait before loading the script.
    <Editor
      tinymceScriptSrc='https://cdn.example.com/tinymce/tinymce.min.js'
      scriptLoading={{
        async: true,
        defer: true,
        delay: 500
      }}
      // ... other props
    />
  8. Reference the available TinyMCE event keys

    main

    The IEvents interface (which combines INativeEvents and ITinyEvents) defines the keys used for event configuration. These keys are used to attach callbacks to the editor lifecycle and user interactions.

    Native Events

    These correspond to standard browser/DOM-like interactions:

    • onBeforePaste, onBlur, onClick, onCompositionEnd, onCompositionStart, onCompositionUpdate, onContextMenu, onCopy, onCut, onDblclick, onDrag, onDragDrop, onDragEnd, onDragGesture, onDragOver, onDrop, onFocus, onFocusIn, onFocusOut, onInput, onKeyDown, onKeyPress, onKeyUp, onMouseDown, onMouseEnter, onMouseLeave, onMouseMove, onMouseOut, onMouseOver, onMouseUp, onPaste, onSelectionChange

    TinyMCE Lifecycle and Editor Events

    These are specific to the TinyMCE editor's internal state and commands:

    • Lifecycle: onInit, onLoadContent, onSetContent, onGetContent, onBeforeSetContent, onBeforeGetContent, onPostRender, onPreProcess, onPostProcess, onRemove, onShow, onHide, onDeactivate, onActivate
    • Content & State: onChange, onDirty, onNodeChange, onSaveContent, onSetContent, onSetAttrib, onVisualAid
    • Undo/Redo: onUndo, onRedo, onAddUndo, onBeforeAddUndo, onClearUndos
    • Commands: onExecCommand, onBeforeExecCommand
    • Object Interaction: onObjectSelected, onObjectResizeStart, onObjectResized
    • Error Handling: onSkinLoadError, onThemeLoadError, onModelLoadError, onPluginLoadError, onIconsLoadError, onLanguageLoadError, onScriptsLoadError
    • Other: onProgressState, onSubmit, onReset, onScriptsLoad