In this tutorial, you will learn how to install TinyMCE into a new or existing React JS application. The steps provided will guide you through the installation process.
Or If you encounter the following error while installing TinyMCE, there is a quick fix available. This error is related to a path issue, and it has been reported by several developers.
Uncaught SyntaxError: Unexpected token '<' (at tinymce.min.js:1:1)
index.js:65776 Uncaught Error: tinymce should have been loaded into global scope
at Editor._this.initialise
Table of Contents
Install TinyMCE Packages:
Install the following packages
npm install --save tinymce @tinymce/tinymce-react fs-extra
Setup a postinstall.js File:
Setup a postinstall script to copy TinyMCE to the public directory for hosting
Create /postinstall.js/ file into root of your application.
const fse = require('fs-extra');
const path = require('path');
const topDir = __dirname;
fse.emptyDirSync(path.join(topDir, 'public', 'tinymce'));
fse.copySync(path.join(topDir, 'node_modules', 'tinymce'), path.join(topDir, 'public', 'tinymce'), { overwrite: true });
Update Package.json file:
Add following script line into your package.json file
{
// ... other content omitted for brevity ...
"scripts": {
// ... other scripts omitted for brevity ...
"postinstall": "node ./postinstall.js"
}
}
Example of Using TineyMCE Editor in ReactJS Component
The following is a quick example that demonstrates how you can integrate the TinyMCE editor into your ReactJS component:
import React, { useRef, useState } from 'react';
import { Editor } from '@tinymce/tinymce-react';
export default function App() {
const editorRef = useRef(null);
const getData = () => {
if (editorRef.current) {
console.log(editorRef.current.getContent());
}
};
return (
<>
<Editor
tinymceScriptSrc='/tinymce/tinymce.min.js'
onInit={(evt, editor) => editorRef.current = editor}
initialValue="<p>This is the initial data.</p>"
init={{
height: 300,
menubar: false,
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 | alignleft aligncenter ' +
'alignright alignjustify | bullist numlist outdent indent | ' +
'removeformat | help',
content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
}}
/>
<button onClick={getData}>Log Content</button>
</>
);
}