javascripthtmlreactjsdangerouslysetinnerhtml

Issue with Text Input Direction in React Component


I'm building a Wysiwyg and I have a content-editable div in my component where users can input and format text. However, there's a problem with the text direction when I try to update the content.

Here's the code snippet:

const [htmlContent, setHtmlContent] = useState("");

[...]

<div
  contentEditable
  className="h-full w-full p-4 text-sm text-gray-600 focus:outline-none dark:text-gray-200"
  dangerouslySetInnerHTML={{ __html: htmlContent }}
  onInput={(e) => setHtmlContent(e.currentTarget.innerHTML)}}
/>

The issue is that when I update e.currentTarget.innerHTML using setHtmlContent(e.currentTarget.innerHTML), the text appears to be reversed. However, if I log e.currentTarget.innerHTML inside the onInput event handler, the text is correct.

Here is a codesandbox

Thank you for your time !


Solution

  • I finaly used onBlur instead of onInput and everything works fine.