ShibinRagh
ShibinRagh

Reputation: 6656

Why document.execCommand not working in reactjs?

I am trying to create simple wysiwyg editor in my react projects but not working document.execCommand ,

I am referring codepen (They used jQuery library here for click function)

Any possible to create simple wysiwyg editor in reactjs ?

//document.addEventListener("click", function (e) {});

    const wrapTag = (role) => {
        switch(role) {
            case 'h1':
            case 'h2':
            case 'p':
              document.execCommand('formatBlock', false, role);
              break;
            default:
              document.execCommand(role, false, null);
              break;
          }
    }

    <div onClick={ () => { wrapTag("bold") } }>bold</div>
     <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eveniet saepe nostrum aspernatur deserunt rem neque ab.</p>

Upvotes: 0

Views: 1154

Answers (1)

Adam Jeliński
Adam Jeliński

Reputation: 1788

You should add an event.preventDefault, to keep the focus:

    const wrapTag = (role) => {
        document.designMode = "on"
        switch(role) {
            case 'h1':
            case 'h2':
            case 'p':
              document.execCommand('formatBlock', false, role);
              break;
            default:
              document.execCommand(role, false, null);
              break;
          }
    }

    <div onClick={ () => wrapTag("bold") } onMouseDown={(event) => 
        event.preventDefault()}>bold</div>
     <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Eveniet saepe nostrum aspernatur deserunt rem neque ab.</p>

Upvotes: 2

Related Questions