Strapi is an open-source headless CMS that gives developers the freedom to choose their favorite tools and frameworks while also allowing editors to manage and distribute their content using their application's admin panel.
In this guide, you will learn how to replace the default WYSIWYG editor (Draftjs) in Strapi with the TinyMCE editor.
To follow through this article, you need to the following: 1. Basic knowledge of JavaScript, 2. Basic knowledge of ReactJS, 3. Basic understanding of Strapi (get started here), 4. A Tiny account (Sign up here), and 5. Node.js (Download and install here.)
This tutorial is heavily based on this guide from the Strapi documentation. The idea here is to create a new field that will be modified to use TinyMCE as its editor, but before we start, there are a few things that we should know:
TinyMCE is NOT a Markdown editor, it's an HTML editor.
This means that the value taken from the field could contain HTML tags like <p>Text</p>
, <img src="..." />
and even <table>...</table>
. Therefore you should be aware of the potential security issues and how to overcome them.
For TinyMCE to work, you will need to obtain an API Key by creating an account at Tinymce (the core editor is free).
Now that we are ready, let's dive into our project.
First, we will create a new project. I will call it my-app
you can call it whatever you like. The --quickstart
option will tell Strapi to create a basic project with default configurations and without templates. This is just to make the process easier and avoid any complications.
yarn create strapi-app my-new-strapi-app --quickstart
#or
npx create-strapi-app my-new-strapi-app --quickstart
After running the command, a new browser tab will open for you to create a new administrator account. If it didn't, head to http://localhost:1337/admin and fill in all the necessary information.
yarn create strapi-app my-app --quickstart
#or
npx create-strapi-app@latest my-strapi-app --quickstart
After running the command, a new browser tab will open for you to create a new administrator account. If it didn't, head to http://localhost:1337/admin and fill in all the necessary information.
Now, we want to generate a new Strapi plugin, but let's first stop Strapi by pressing Ctrl+C
or Command+C
and cd
into the project directory. Make sure to replace "my-app" with your project name
cd my-new-strapi-app
We will call our plugin wysiwyg
so we should run:
yarn strapi generate
Choose "plugin" from the list, press Enter and name the plugin wysiwyg
.
Enable the plugin by adding the code below to the plugins configurations file:
1 // path: ./config/plugins.js
2
3 module.exports = {
4 wysiwyg: {
5 enabled: true,
6 resolve: "./src/plugins/wysiwyg", // path to plugin folder
7 },
8 };
To use TinyMCE, we will need to install its library, and because Strapi is using React, we will install the TinyMCE library for React @tinymce/tinymce-react
. But first, let's cd
into the newly created plugin and only then install it there:
cd src/plugins/wysiwyg
And then,
yarn add @tinymce/tinymce-react
#or
npm install @tinymce/tinymce-react
Start the application with the front-end development mode:
# Go back to the application root folder
cd ../../..
yarn develop --watch-admin
Note: Launching the Strapi server in watch mode without creating a user account first will open localhost:1337
with a JSON format error. Creating a user on localhost:8081
prevents this alert.
We now need to create our new WYSIWYG, which will replace the default one in the Content Manager.
In step 2, we generated the necessary files for any plugin. Now, we need to make it ours by creating a few files to tell Strapi what to do with this plugin. So first, we will create the necessary directories and files (React Components), then we will write into them.
To create the directories and files (make sure you are inside the plugin directory (.../src/plugins/wysiwyg
):
cd admin/src/components
#The following will create .../MediaLib/index.js
mkdir -p MediaLib && cd MediaLib && touch index.js
#The following will create .../Wysiwyg/index.js
cd .. && mkdir -p Wysiwyg && cd Wysiwyg && touch index.js
#The following will create .../Tinymce/index.js
cd .. && mkdir -p Tinymce && cd Tinymce && touch index.js
This file will handle the insertion of media i.e. insert media (images, video...etc) to TinyMCE editor. It's important to notice here that we are using Strapi Media Library to handle the media instead of letting TinyMCE handle it, and that's perfect because we don't want to let the user (The person who is using the Editor) insert media from somewhere else, so make sure NOT to allow such insertion in TinyMCE settings (More on that later).
Now using your favorite editor (I am using VS Code), open the file code ./components/MediaLib/index.js
, paste the following code and save:
1 // ./src/plugins/wysiwyg/admin/src/components/MediaLib/index.js
2
3 import React from 'react';
4 import { prefixFileUrlWithBackendUrl, useLibrary } from '@strapi/helper-plugin';
5 import PropTypes from 'prop-types';
6 const MediaLib = ({ isOpen, onChange, onToggle }) => {
7 const { components } = useLibrary();
8 const MediaLibraryDialog = components['media-library'];
9 const handleSelectAssets = (files) => {
10 const formattedFiles = files.map((f) => ({
11 alt: f.alternativeText || f.name,
12 url: prefixFileUrlWithBackendUrl(f.url),
13 mime: f.mime,
14 }));
15 onChange(formattedFiles);
16 };
17 if (!isOpen) {
18 return null;
19 }
20 return (
21 <MediaLibraryDialog
22 onClose={onToggle}
23 onSelectAssets={handleSelectAssets}
24 />
25 );
26 };
27 MediaLib.defaultProps = {
28 isOpen: false,
29 onChange: () => {
30 },
31 onToggle: () => {
32 },
33 };
34 MediaLib.propTypes = {
35 isOpen: PropTypes.bool,
36 onChange: PropTypes.func,
37 onToggle: PropTypes.func,
38 };
39 export default MediaLib;
This file will be the wrapper of TinyMCE editor, it will display the labels and handle the error messages as well as inserting media. An important thing to notice here is that this code is only handling images. Further steps are required to handle videos and other media.
Again, using your favorite editor, open the file code ./components/Wysiwyg/index.js
and paste the following code:
Note: If you get
file not found
error around theimport TinyEditor...
Ignore it for now as we will create it in the next step.
1 // ./src/plugins/wysiwyg/admin/src/components/Wysiwyg/index.js
2
3 import React, { useState } from 'react';
4 import PropTypes from 'prop-types';
5 import { Stack } from '@strapi/design-system/Stack';
6 import { Box } from '@strapi/design-system/Box';
7 import { Button } from '@strapi/design-system/Button';
8 import { Typography } from '@strapi/design-system/Typography';
9 import Landscape from '@strapi/icons/Landscape';
10 import MediaLib from '../MediaLib';
11 import Tinymce from '../Tinymce';
12 import { useIntl } from 'react-intl';
13 const Wysiwyg = ({
14 name,
15 onChange,
16 value,
17 intlLabel,
18 disabled,
19 error,
20 description,
21 required,
22 }) => {
23 const { formatMessage } = useIntl();
24 const [mediaLibVisible, setMediaLibVisible] = useState(false);
25 const handleToggleMediaLib = () => setMediaLibVisible((prev) => !prev);
26 const handleChangeAssets = (assets) => {
27 let newValue = value ? value : '';
28 assets.map((asset) => {
29 if (asset.mime.includes('image')) {
30 const imgTag = `<p><img src="${asset.url}" alt="${asset.alt}"></img></p>`;
31 newValue = `${newValue}${imgTag}`;
32 }
33 // Handle videos and other type of files by adding some code
34 });
35 onChange({ target: { name, value: newValue } });
36 handleToggleMediaLib();
37 };
38 return (
39 <>
40 <Stack size={1}>
41 <Box>
42 <Typography variant="pi" fontWeight="bold">
43 {formatMessage(intlLabel)}
44 </Typography>
45 {required && (
46 <Typography variant="pi" fontWeight="bold" textColor="danger600">
47 *
48 </Typography>
49 )}
50 </Box>
51 <Button
52 startIcon={<Landscape />}
53 variant="secondary"
54 fullWidth
55 onClick={handleToggleMediaLib}
56 >
57 Media library
58 </Button>
59 <Tinymce
60 disabled={disabled}
61 name={name}
62 onChange={onChange}
63 value={value}
64 />
65 {error && (
66 <Typography variant="pi" textColor="danger600">
67 {formatMessage({ id: error, defaultMessage: error })}
68 </Typography>
69 )}
70 {description && (
71 <Typography variant="pi">{formatMessage(description)}</Typography>
72 )}
73 </Stack>
74 <MediaLib
75 isOpen={mediaLibVisible}
76 onChange={handleChangeAssets}
77 onToggle={handleToggleMediaLib}
78 />
79 </>
80 );
81 };
82 Wysiwyg.defaultProps = {
83 description: '',
84 disabled: false,
85 error: undefined,
86 intlLabel: '',
87 required: false,
88 value: '',
89 };
90 Wysiwyg.propTypes = {
91 description: PropTypes.shape({
92 id: PropTypes.string,
93 defaultMessage: PropTypes.string,
94 }),
95 disabled: PropTypes.bool,
96 error: PropTypes.string,
97 intlLabel: PropTypes.shape({
98 id: PropTypes.string,
99 defaultMessage: PropTypes.string,
100 }),
101 name: PropTypes.string.isRequired,
102 onChange: PropTypes.func.isRequired,
103 required: PropTypes.bool,
104 value: PropTypes.string,
105 };
106 export default Wysiwyg;
This is where all the work is done, it's the file that will implement the editor
Note: mark this file as we will revisit it to configure TinyMCE.
One more time, using your favorite editor, open the file nano ./components/Tinymce/index.js
and paste the following code:
Note: Make sure to replace
API_KEY
with the actual key you obtained from TinyMCE.
1 import React from "react";
2 import PropTypes from "prop-types";
3 import { Editor } from "@tinymce/tinymce-react";
4 const TinyEditor = ({ onChange, name, value }) => {
5 return (
6 <Editor
7 apiKey="API KEY"
8 value={value}
9 tagName={name}
10 onEditorChange={(editorContent) => {
11 onChange({ target: { name, value: editorContent } });
12 }}
13 outputFormat="text"
14 init={{}}
15 />
16 );
17 };
18 TinyEditor.propTypes = {
19 onChange: PropTypes.func.isRequired,
20 name: PropTypes.string.isRequired,
21 value: PropTypes.string,
22 };
23 export default TinyEditor;
Our plugin is ready and waiting, but Strapi doesn't know about it yet. Hence, we need to register it with Strapi and give some information about it. To do so, we will edit one last file (The file is already there, we will just change the code inside it).
Again, using your favorite editor, open the file:
Note: Make sure you are still inside the plugin folder
1`...src/plugins/wysiwyg/admin/src/index.js`
2
3
4 // src/plugins/wysiwyg/admin/src/index.js
5
6 import { prefixPluginTranslations } from '@strapi/helper-plugin';
7 import pluginPkg from '../../package.json';
8 import pluginId from './pluginId';
9 import Initializer from './components/Initializer';
10 import PluginIcon from './components/PluginIcon';
11 import Wysiwyg from "./components/Wysiwyg"
12 const name = pluginPkg.strapi.name;
13 export default {
14 register(app) {
15 app.addMenuLink({
16 to: `/plugins/${pluginId}`,
17 icon: PluginIcon,
18 intlLabel: {
19 id: `${pluginId}.plugin.name`,
20 defaultMessage: name,
21 },
22 Component: async () => {
23 const component = await import(/* webpackChunkName: "[request]" */ './pages/App');
24 return component;
25 },
26 });
27 app.addFields({ type: "wysiwyg", Component: Wysiwyg });
28 app.registerPlugin({
29 id: pluginId,
30 initializer: Initializer,
31 isReady: false,
32 name,
33 });
34 },
35 bootstrap(app) { },
36 async registerTrads({ locales }) {
37 const importedTrads = await Promise.all(
38 locales.map(locale => {
39 return import(
40 /* webpackChunkName: "translation-[request]" */ `./translations/${locale}.json`
41 )
42 .then(({ default: data }) => {
43 return {
44 data: prefixPluginTranslations(data, pluginId),
45 locale,
46 };
47 })
48 .catch(() => {
49 return {
50 data: {},
51 locale,
52 };
53 });
54 })
55 );
56 return Promise.resolve(importedTrads);
57 },
58 };
Let's get back to the project folder:
cd ../../../../
# After running this command I will be at .../my-new-strapi-app
# Make sure you are in .../<your-project-name>
Finally, Start Strapi with the front-end development mode --watch-admin
:
yarn develop --watch-admin
#or
npm run develop -- --watch-admin
#or
strapi develop --watch-admin
When you run the last command, it will open a new tab in the browser (if it didn't, head to localhost:8000/admin) and log in with the administrator account you created earlier.
From the menu on the left go to Content-Types Builder
so we can create new content for testing. Choose Create new single type
.
Enter a display name like episode
.
Choose Rich Text. Give it a name like Description
and hit Finish
.
From the top right corner, hit Save
, and wait for the server to restart In the left menu, you will find the newly created content episode
, press it to edit it. And hop!, there you go, TinyMCE is working! Yaaay 😍.
Hmm 😕 , something isn't quite right yet! You are probably not able to insert a new line or do pretty much anything useful. Don’t stop Strapi just yet! Since we started Strapi with --watch-admin
mode, we don’t need to stop it, and we will still be able to see the changes we will make as we are doing them (Cool ha? 😎).
Remember the file we marked? In that file, we need to configure TinyMCE to work for us as we expect it to do. we need to tell TinyMCE three important things.
From the project directory, open the file using your favorite editor code plugins/wysiwyg/admin/src/components/Tinymce/index.js
.
And do the following changes:
To make full use of TinyMCE, we will tell it to deal with the input as an HTML and give the output as an HTML too,
Change: outputFormat='text'
To: outputFormat='html'
inside init={{}}
add: selector: 'textarea',
this is to tell Strapi that we are using <textarea></textarea>
tags for input.
This is where all the fun is. again, inside init={{}}
and after the previously added selector
, add two things:
plugins: '',
Here we will add all the features and functionalities that we want TinyMCE to have.toolbar: '',
It's also for adding features, but those who are added here will appear directly in the top toolbar of TinyMCE, while the ones we added earlier will appear in a drop-down menu.Note: Add all the plugins you want between the single quotes
' HERE '
and separate them with single spaces, A full list can be found here, Remember not to add any plugin that allows users to upload the media directly to the editor.
When you are done picking from the TinyMCE plugins, the final version of the file will look something like this:
#PATH: <your-projectname>/src/plugins/wysiwyg/admin/src/components/Tinymce/index.js
1 // /src/plugins/wysiwyg/admin/src/components/Tinymce/index.js
2
3 import React, { useRef } from 'react';
4 import { Editor } from '@tinymce/tinymce-react';
5 import PropTypes from 'prop-types';
6 const TinyEditor = ({ onChange, name, value, disabled }) => {
7 const onChangeRef = useRef(onChange);
8 function onBlur(ev, editor) {
9 const content = editor.getContent();
10 onChangeRef.current({ target: { name, value: content, type: 'wysiwyg' } });
11 }
12 return (
13 <>
14 <Editor
15 apiKey={process.env.TINY_API}
16 value={value}
17 tagName={name}
18 onEditorChange={(editorContent) => {
19 onChange({ target: { name, value: editorContent } });
20 }}
21 outputFormat='html'
22 init={{
23 selector: 'textarea',
24 plugins: 'fullscreen insertdatetime .... MORE PLUGINS',
25 toolbar: 'code numlist bullist .... MORE PLUGINS',
26 }}
27 />
28 </>
29 );
30 }
31 TinyEditor.defaultProps = {
32 value: '',
33 };
34 TinyEditor.propTypes = {
35 onChange: PropTypes.func.isRequired,
36 name: PropTypes.string.isRequired,
37 value: PropTypes.string,
38 };
39 export default TinyEditor;
Because Strapi is still running, we can add some plugins and try it out, then add some more and so on… and when we are all set and ready to see it in action, we can now stop Strapi and start it fresh again. Press Ctrl+C
or Command+C
to stop Strapi.
Head back to the root directory
1cd ../../..
Now Let’s run it without --watch-admin
, but after we build it clean:
yarn build
yarn develop
#OR
npm run build
npm run develop
#OR
strapi build
strapi develop
After running the commands, a new browser tab should open. If it didn't, head to localhost:1337/admin. Now go back to our episode
and give it another try, everything should be working fine 😆.
Congratulations! 🥳🥳 Now, we have a special Strapi field that is using TinyMCE as its editor. This will open the creativity doors for your users. It’s important to spend some time making sure that you only get the plugins that you need from TinyMCE. You should also know that even if you disabled some plugins from the editor, users will still be able to copy-paste some “Formatted Text” from other places (Formatted text is a cooler name for “text with Style appended to it (CSS and possibly JavaScript in our case)”). Enjoy the Intelligence and Power of Strapi combined with the flexibility of TinyMCE.
Software Engineer focused on building web applications and writing technical content.