react-runner icon indicating copy to clipboard operation
react-runner copied to clipboard

Using onChange to store value in state results in jumping keyboard cursor

Open antun opened this issue 2 years ago • 0 comments

I'm not sure if this is a bug or I'm not following the correct pattern. I need to store the code that the user edited in the state. (In my app, I'm using Redux, but I've simplified it to just React state with useState for this example.)

import { useState } from 'react'
import {
  LiveProvider,
  LiveEditor,
  LiveError,
  LivePreview,
} from 'react-live-runner'
import './App.css'

function App() {
  const [count, setCount] = useState(0)
  const initCode = `<div>
  Hello, world!
</div>`;
  const [code, setCode] = useState(initCode);
  const handleChange = (newCode) => {
    setCode(newCode);
  };

  return (
    <>
      <LiveProvider code={code}>
        <LiveEditor onChange={handleChange} />
        <LivePreview />
        <LiveError />
      </LiveProvider>
      <hr />
      <div>code:</div>
      <pre>
        {code}
      </pre>
    </>
  )
}

export default App              

When I type into the LiveEditor, the first character is inserted into the correct place. However, after that,the cursor jumps to the end of the LiveEditor, and any following characters are inserted there.

I figured saving the code in state is probably fairly common, so maybe I'm just not following the right pattern here?

antun avatar Jul 17 '23 23:07 antun