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>
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>