Skip to content

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

@antun

Description

@antun

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions