Have you been losing sleep over the ugliness and simplicity of ordinary rich text editors? Do you crave the ability to upload files, preview online, edit spreadsheets, etc.? Follow my lead and create an easy-to-use and powerful rich text editor, Tinymce-React!

This article will not say too much, aims to use the fastest speed to help you realize your dream! (Whatever your dream is, say it!)

1. Install

npm install --save @tinymce/tinymce-reactCopy the code

or

yarn add --save @tinymce/tinymce-reactCopy the code

2. Apply for a free apiKey

This step is very convenient, as long as your hand speed is as fast as mine, no more than three minutes

Address: www.tiny.cloud/get-tiny/

3. Introduce the React

import { Editor } from '@tinymce/tinymce-react'Copy the code

Yes, it’s that simple!!

4. Basic

 <Editor    
    inline={false}    
    selector='editorStateRef'      
    apiKey='your key'    
    ref='tinyEditor'    
    value={this.state.content}    
    onEditorChange={this.handleEditorChange}    
    init={{        
        height: '100%',        
        plugins: 'table lists image',        
        toolbar: `formatselect | image |  bold italic strikethrough forecolor backcolor
        alignleft aligncenter alignright alignjustify
        numlist bullist outdent indent`,
        file_picker_types: 'image',
        // automatic_uploads={false}        
        images_upload_url: ' ',        
        image_uploadtab: true,     }}  />  
        handleEditorChange = (content, editor) => {    
        console.log('Content was updated:', content);  
    }Copy the code

Obviously, this already does what you want!

Images_upload_url write your image interface, the front of the students can write their own upload interface, beg rather than beg their own!!

4. Upload interface

I decided to post a simple upload interface directly to help you test. The following is Express.

// index.js
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const multer = require('multer');
const pathLib = require('path');
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(multer({dest: './dist'}).array('file')); 
app.use(The '*'.function (req, res, next) {    
    res.header("Access-Control-Allow-Origin"."*");    
    res.header("Access-Control-Allow-Headers"."Content-Type,Content-Length, Authorization, Accept,X-Requested-With");    
    res.header("Access-Control-Allow-Methods"."PUT,POST,GET,DELETE,OPTIONS");    
    res.header("X-Powered-By".'3.2.1');    
    if(req.method=="OPTIONS") res.send(200);    
        else  next();
    });
    app.post('/file_upload'.function(req, res){    
        console.log(req.files[0]);    
        fs.readFile(req.files[0].path, function(err, data){        
            if(err){            
                console.log('Error');        
            }else{            
                var dir_file = __dirname + '/' + req.files[0].originalname            
                // console.log(dir_file);            
                fs.writeFile(dir_file, data, function(err){                
                var obj = {                    
                    msg: 'upload success',                    
                    filename: req.files[0].originalname,                    
                    location :"https://www.baidu.com/img/bd_logo1.png?where=super",                
               }                
            res.send(JSON.stringify(obj));            
        })        
      }    
   })
})
var server = app.listen(8081, function(){    
var host = server.address().address;    
var port = server.address().port;    
console.log('Server is running at http://127.0.0.1:8081'); })Copy the code

Start: node index.js

How do YOU install express? See the size of my punching bag?!

See the location parameter? That’s right, that’s why I’m giving you the interface. The server must have this parameter in order for your page to display images.

5. Upload files

Idle talk less talk, let us achieve their own upload file!

 <Editor    
    inline={false}    
    selector='editorStateRef'      
    apiKey='your key'    
    ref='tinyEditor'    
    value={this.state.content}    
    onEditorChange={this.handleEditorChange}    
    init={{        
        height: '100%',        
        plugins: 'table lists link image', toolbar: `formatselect | link image | bold italic strikethrough forecolor backcolor alignleft aligncenter alignright alignjustify  numlist bullist outdent indent`, file_picker_types:'file image media',        
        file_picker_callback: this.file_picker_callback,        
        // automatic_uploads={false}        
        images_upload_url: ' ',        
        image_uploadtab: true,     
    }}  />  
handleEditorChange = (content, editor) => {    
    console.log('Content was updated:', content);  
}Copy the code

See the difference? File_picker_types, plugins, toolbar changed.

file_picker_callback: function (callback, value, meta) {
        var filetype='.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4';
        var upurl='/demo/upfile.php';
        switch(meta.filetype){
            case 'image':
                filetype='.jpg, .jpeg, .png, .gif';
                upurl='upimg.php';
                break;
            case 'media':
                filetype='.mp3, .mp4';
                upurl='upfile.php';
                break;
            case 'file'Var input = document.createElement('input');
            input.setAttribute('type'.'file');
            input.setAttribute('accept', filetype);
        input.click();
        input.onchange = function() {
            var file = this.files[0];

            var xhr, formData;
            console.log(file.name);
            xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', upurl);
            xhr.onload = function() {
                var json;
                if(xhr.status ! = 200) { failure('HTTP Error: ' + xhr.status);
                    return;
                }
                json = JSON.parse(xhr.responseText);
                if(! json || typeof json.location ! ='string') {
                    failure('Invalid JSON: ' + xhr.responseText);
                    return;
                }
                callback(json.location);
            };
            formData = new FormData();
            formData.append('file', file, file.name );
            xhr.send(formData);
        };Copy the code

The chestnut would do just fine.

Why is the upload blank after successful?



Fill in the value here! If you want to automatically write the filename to the input, there are many ways, I’m sure you can!

Finally, attached document:

English: www.tiny.cloud/docs/

English: tinymce. Ax – z.c n/general/bas…

City south small road meet spring again, see plum blossom to see a person. There are three thousand diseases of life and death, but poverty cannot be cured!

For sacks, you use Vue? Don’t panic, next time we will introduce the more powerful Froala. If you are in a hurry, go ahead!

Farewell, ladies and gentlemen!