How To Make Simple Text Editor Using Javascript In React-JS

Hello Developers, In this blog, we will learn how we can make a simple text editor in react js using javascript

There are plenty of plugins available for this, but we are not going to use them we will use simple javascript for this

We are going to use document.execCommand() method to make this possible

First, make a new app using the following command

npx create-react-app

Then add this code to your js file

<div style={{ display: 'flex', gap: '15px' }}>
  <Button onClick={(e) => {
    document.execCommand('bold')
  }}>B</Button>
  <Button style={{ fontStyle: 'italic' }} onClick={(e) => {
    document.execCommand('italic')
  }}>I</Button>
  <Button style={{ textDecoration: 'underline' }} onClick={(e) => {
    document.execCommand('underline')
  }}>U</Button>
</div>
<div
  contentEditable
  spellCheck='false'
  style={{
    background: '#f7f7fa',
    padding: '15px',
    width: '25%'
  }}
>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and 
 scrambled it to make a type specimen book.</div>

Make sure you have an element with contentEditable set true to use this feature

In my case, I am using div with contentEditable true

What happens when you set contentEditable to true?

It allows you to edit the content of that element like input or textarea element

Demo:

You can use more features also like increase-decrease font size, change font color, change background-color etc.

API reference:- https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories