How To Integrate A Rich Text Editor (WYSIWYG) In Your React.Js Project.
Lucius Emmanuel Emmaccen

Lucius Emmanuel Emmaccen @emmaccen

About: Senior Software Engineer. I love building cool stuffs

Joined:
Apr 23, 2020

How To Integrate A Rich Text Editor (WYSIWYG) In Your React.Js Project.

Publish Date: Jul 10 '20
131 32

In this article, we're going to learn how to "Integrate A Rich Text Editor" in your react.Js project using TinyMCE.

Before we begin, let's do a quick summary of what a "Rich Text Editor" also commonly known as (WYSIWYG) what-you-see-is-what-you-get means, just in case you found this article out of curiosity.

In simple terms: A Rich Text Editor is an interface for editing rich text within browsers, which could also include images, links, audio and videos in a what-you-see-is-what-you-get fashion. These editors aim to reduce the effort for users trying to express their formatting directly as valid HTML markup.

These editors (There're quite a number of them) can particularly be useful if you're creating your very own blog website 😎.
Now that we have a clear understanding of what a Rich Text Editor is, let's get right into it.

Prerequisites

  • Node.js (and npm)
  • Access to tinymce.min.js on either : Tinycloud or TinyMCE Self-hosted (what we'll be using) See Installing TinyMCE for details on self-hosting TinyMCE.
  • Basic React Knowledge. Don't worry if you're a beginner, you can do this !.

Procedures | Processes

  1. If you don't already have React installed on your machine, open your command line or command prompt and install the Create React App package.
 $ npm install -g create-react-app
Enter fullscreen mode Exit fullscreen mode
  1. Create a new React project and "name it anything you want". I named mine WYSIWYG
 $ create-react-app WYSIWYG
Enter fullscreen mode Exit fullscreen mode
  1. Change into the newly-created directory.
 $ cd WYSIWYG
Enter fullscreen mode Exit fullscreen mode
  1. Install the TinyMCE-react package and save it to your package.json with --save.
 $ npm install --save @tinymce/tinymce-react
Enter fullscreen mode Exit fullscreen mode
  1. Open the project using any editor of choice. I use VScode

Code Image

  1. Inside the Public folder, let's open the Index.html file and paste this code at the head section ( some paste at the bottom... your choice 😎)
<script src="/path/to/tinymce.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Now that we have a project all set up for our Rich Text Editor, let's start with the INTEGRATION so we can all be happy.

Navigate to your "src" directory and :

  • Create a "components" folder inside the "src" directory
  • Inside the "components" folder, create a "RichText.js" file.

project hierarchy

  • After you've done that, paste the code below into your RichText.js file

import React from 'react';
import { Editor } from '@tinymce/tinymce-react';

class RichText extends React.Component {
  handleEditorChange = (e) => {
    console.log(
      'Content was updated:',
      e.target.getContent()
    );
  }

  render() {
    return (
      <Editor
        initialValue="<p>Wow ! ... It Works !!!</p>"
        init={{
          height: 500,
          menubar: false,
          plugins: [
            'advlist autolink lists link image',
            'charmap print preview anchor help',
            'searchreplace visualblocks code',
            'insertdatetime media table paste wordcount'
          ],
          toolbar:
            'undo redo | formatselect | bold italic | \
            alignleft aligncenter alignright | \
            bullist numlist outdent indent | help'
        }}
        onChange={this.handleEditorChange}
      />
    );
  }
}

export default RichText;
Enter fullscreen mode Exit fullscreen mode

Pasting the above code will create a react component containing the TinyMCE editor.

  • Now let's navigate to our App.js folder and import the RichText component so we can have it rendered in the browser.
import React from 'react';
import RichText from './component/RichText'
function App() {
  return (
    <div className="App">
      <RichText />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode
  • To run the app lets open the terminal and run this code (make sure you've checked into your project directory in the terminal. e.g cd pathToProject ) :
  $ npm run start
Enter fullscreen mode Exit fullscreen mode

Now you should see the application up and running in the browser (usually localhost:3000)

Rich Text Editor

That was easy ? wasn't it ??

But we're not done just yet !. Did you notice a warning that pops up in the editor when you try to type anything ( Warning: This domain is not registered with Tiny Cloud ) ??. That's because we've not created an API key.

Don't worry We've completed the easy part, now for the easier part, all that's left is to get rid of that scary warning, but... How do we do that ? well... It's easy 😎.

Let's Follow These Steps

  • To get an API Key Let's go to the tinycloud page and create an account.
  • fill in the basic Infos they'll ask (Nothing Personal)
  • They'll send a confirmation email, so we'd have to open our mail and confirm by clicking the link provide (this redirects to a page where we'll do basic setups)
  • On the redirect page, we'll add our domain (if we have one e.g ...mycooldomain.com), localhost is by default and we don't have to explicitly include that.
  • Next, we scroll to the bottom of the page and click on Continue to dashboard. This is where we'll see our API KEY
  • Copy the API KEY and navigate to the RichText.js file. Inside the <Editor /> component, include the apiKey option in the editor element and paste your TinyMCE API key.
<Editor
  apiKey="your-api-key-goes-here"
  init={{ /* your other settings */ }}
/>
Enter fullscreen mode Exit fullscreen mode

Save the project and watch the magic happen. Voila! We don't have errors anymore !!!.

Check out the working code on my Git repository. Please feel free to fork the project.
There's a lot that can be done with TinyMCE, to explore some more goodies there is, go check out the TinyMCE docs. Also, it can be integrated with other technologies too, such as Angular, Vue etc.
TinyMCE can be customised to include a lot more plugins and Event bindings than we currently have in our project.

PRO TIPS

  • If you wish to add some spacing (margins or padding) outside the <Editor />, just wrap a <div></div> around it and style accordingly.
  • To make this project more fun, create a git Repo and push all you've learnt in this post.
  • Teach someone else 😎
  • Don't forget to give a thumbs Up and leave comments (please, I love feedbacks)
  • last but not least, This is my first ever blog post so, don't hesitate to point out errors to help me improve.

Thanks to everyone that took the time out to read this blog and once again, be sure to check out the working code on my Git repository, if you so wish.
Please, feel free to fork and star the project. I wish you all the best.

Comments 32 total

  • Oluwatosin017
    Oluwatosin017Jul 10, 2020

    That's really cool. Can't wait to try this out.

  • Frankinstein Stone
    Frankinstein StoneJul 10, 2020

    I love your works sir. Keep up the good work

  • Deepak Shrivastava
    Deepak ShrivastavaJul 10, 2020

    Worked for me.... thank you Emmanuel fir sharing this.... ✌️✌️✌️😇😇

  • Yezy Ilomo
    Yezy IlomoJul 10, 2020

    Good work. Just a reminder don't store your API key in your React App, save it in environment file like .env.local or .env.production as
    REACT_APP_TINYMCE_API_KEY=your-api-key-here
    and retrieve it by using process.env.REACT_APP_TINYMCE_API_KEY in your react App.

    • Lucius Emmanuel Emmaccen
      Lucius Emmanuel EmmaccenJul 10, 2020

      Wow ! Real helpful feedback. I'll be sure to do that. Thanks for this 🙏🏽💯

    • Anurag Hazra
      Anurag HazraJul 10, 2020

      I think as long as those API keys are public keys those are fine.

      Also note that you cannot hide API keys on FrontEnd because they will be included anyways in the production build

      create-react-app.dev/docs/adding-c...

      Just don't store any SECRET_KEYs in frontend

    • Daniel Albuschat
      Daniel AlbuschatJul 10, 2020

      Good advice, but please don't believe that they are secured when you store them in env vars. They're still part of the JavaScript code delivered to the browser, and hence can be viewed by anybody, e.g. via DevTools.

    • Grant Watson
      Grant WatsonJul 11, 2020

      This is something I need to remember to do. I have to refactor my repos on GitHub to remove them

    • Prateek Parmar
      Prateek ParmarAug 2, 2020

      Does it apply for next.js applications as well?I'm using it in a next js project.

  • Yash Soni
    Yash SoniJul 10, 2020

    A really descriptive one. Trying out today for one of my pet Project. Just curious, how do you compare this with Facebook’s Draft.js? Have you tried that?

  • Twittingpoet
    TwittingpoetJul 10, 2020

    Very great work. Thanks

  • rasta_alli
    rasta_alliJul 10, 2020

    Good Job keep up the good work bro.. So proud of you Emmaccen💯

  • Abbie
    AbbieJul 10, 2020

    Love this😍😍

  • fashakinsamuel
    fashakinsamuelJul 10, 2020

    Well I tried it and it works....
    Good work bro send me a direct message on Facebook let's talk on the app I want you to develop for me.....

    Once again this is a job well done....#👍

  • Hardaeborla
    HardaeborlaJul 10, 2020

    Wow! This is really helpful

  • Mike Jefe
    Mike JefeJul 10, 2020

    nice work.

  • diddymagic
    diddymagicJul 10, 2020

    wow you give unique insights, remarkable work , I want to suggest you also do a vlog or you tube cos this would help alot out there. Thank you and well done again

  • Adeniyi Adekunle
    Adeniyi AdekunleNov 3, 2020

    Great

  • asitsi
    asitsiNov 9, 2020

    how to send data using tinymce,WYSIWYG through API ...?

    • Lucius Emmanuel Emmaccen
      Lucius Emmanuel EmmaccenNov 10, 2020

      Hi, "Asitsi".
      One way to do this is :
      If you go over the code snippets I provided in the article, you'd notice a handleEditorChange function.

        handleEditorChange = (e) => {
          console.log(
            'Content was updated:',
            e.target.getContent()
          );
        }
      
      Enter fullscreen mode Exit fullscreen mode

      So with this function, you can grab the values using the e.target.getContent() and store the value in SetState after which you can then access the stored values and send to your API.

      Let me know if this helps, thanks.

Add comment