Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

313
Views
React: change contentEditable div's state and maintain cursor

I am developing a writing app for my admin panel, and it has a multilingual state... so each input box looks like this:

<input
  type='text'
  name='title'
  placeholder='title'
  onInput={
    e => setPostState({
      ...postState,
      [lang]: {
        ...postState[lang],
        title: e.target.value
      }
    }) }
  value={ postState[lang].title }
/>

It works perfectly, I can type whatever, and if I switch languages it switches value, the value syncs with the state and there's no problem with the cursor... until I get to a custom contentEditable div input (which acts as an HTML editor, complete with syntax highlighting):

<Editor
  editorRef={ Ref.editor }
  onInput={ txt => ... }
  value=...
/>

My editor handles input with this function:

const handleInput = e =>
{
  const { current: editor } = editorRef;
  onInput(editor.textContent);
  doHighlight(editor);
  e.preventDefault();
}

and updates its textContent based on its value here:

useEffect(() =>
{
  if (value) editorRef.current.textContent = value;
}, [ value ]);

Problem is, is that the state reload from value triggers the component to render... which resets the cursor. Why is this not a problem on a normal input component, and how can I emulate this behavior in a div?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!