Caret position reverts to start of contenteditable span on re-render in React in Safari and Firefox Caret position reverts to start of contenteditable span on re-render in React in Safari and Firefox reactjs reactjs

Caret position reverts to start of contenteditable span on re-render in React in Safari and Firefox


You can achieve a contenteditable by adding a handler to an HTML tag.The problem is every time content is re-rendered the position of the cursor is reset. You are triggering a setState when the content of the span is edited, which is resetting the cursor position.

You could rather store a reference to the span tag and update its value rather than triggering a state change.

A ref could be stored which will inject the value in the span.

class ContentEditable extends Component {  constructor(props) {    super(props);    this.spanRef = React.createRef();    this.val = props.value;  }  handleInput(event) {    const { innerText } = event.target;    if (this.val !== innerText) {      this.spanRef.innerText = innerText;      this.val = innerText;    }  }  render() {    return (      <span        contentEditable="true"        className={"is-valid"}        onInput={this.handleInput.bind(this)}        ref={this.spanRef}        suppressContentEditableWarning={true}      >        {this.val}      </span>    );  }}

Running code