Issue with Text Input Direction in React Component

84 views Asked by At

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 !

2

There are 2 answers

0
Johan On BEST ANSWER

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

0
moon On

The cursor out of focus after setHtmlContent running,and then the cursor's position will be set to begin,so I add a useEffect function to move the cursor's position to end

useEffect(() => {
  const div = document.querySelector('.h-full.w-full.p-4')
  div.focus()
  document.execCommand("selectAll", false, null);
  document.getSelection().collapseToEnd();
}, [htmlContent])