Thursday, 25 February 2021

TinyMCE Self-hosted with React

i am trying to create a simple self-hosted TinyMCE with react. Currently my project is just show a simple textarea there is no toolbar or any style. I think a good way to integrate tinymce is by using a module loader. I read that react already includes webpack by using npx create-react-app.

Projectstructor
    root
    |-public
    |-skins
    |-src 
       |-App.js
       |-TinyEditorComponent.js
    |-webpack.config.js

What I have done step by step:

  1. npx create-react-app my-app

  2. $ npm install --save @tinymce/tinymce-react

  3. cp -r node_modules/tinymce/skins skins

  4. create file webpack.config.js

const config = {
  module: {
    loaders: [
      {
        test: require.resolve("tinymce/tinymce"),
        loaders: ["imports?this=>window", "exports?window.tinymce"],
      },
      {
        test: /tinymce\/(themes|plugins)\//,
        loaders: ["imports?this=>window"],
      },
    ],
  },
};

TextEditor Component:

import React, { Component } from "react";

// Import TinyMCE
import tinymce from "tinymce/tinymce";

// Default icons are required for TinyMCE 5.3 or above
import "tinymce/icons/default";

// A theme is also required
import "tinymce/themes/silver";

// Any plugins you want to use has to be imported
import "tinymce/plugins/paste";
import "tinymce/plugins/link";

class TinyEditorComponent extends Component {
  constructor() {
    super();
    this.state = { editor: null };
  }

  componentDidMount() {
    tinymce.init({
      selector: `#${this.props.id}`,
      skin_url: `./skins/content/dark`,
      plugins: [
        "advlist autolink lists link image charmap print preview anchor",
        "searchreplace visualblocks code fullscreen",
        "insertdatetime media table paste code help wordcount",
      ],
      toolbar: "undo redo | formatselect | bold italic backcolor |",
      setup: editor => {
        this.setState({ editor });
        editor.on("keyup change", () => {
          const content = editor.getContent();
          this.props.onEditorChange(content);
        });
      },
    });
  }

  componentWillUnmount() {
    tinymce.remove(this.state.editor);
  }

  render() {
    return (
      <textarea
        id={this.props.id}
        value={this.props.content}
        onChange={e => console.log(e)}
      />
    );
  }
}

export default TinyEditorComponent;

I am not sure how to override and configure webpack for tinymce, there are alot of old ways but what is the right one. By injecting webconfig?



from TinyMCE Self-hosted with React

No comments:

Post a Comment