From 05cd8372dcbda4ef44666b3bd2362845d271ec42 Mon Sep 17 00:00:00 2001 From: Lionel T Date: Sun, 29 Apr 2018 23:57:24 +0200 Subject: [PATCH] Fix caret position after update Avoid the cursor to jump to the end of the `input` after update the `state`. Fix the warining _uncontrolled input of type text to be controlled_ due to `state` initialized with **content** key in the `constructor` but then used as **value** key. --- pages/index.js | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/pages/index.js b/pages/index.js index 9cca907..919c3c3 100644 --- a/pages/index.js +++ b/pages/index.js @@ -9,7 +9,7 @@ class Index extends PureComponent { super(props) this.state = { - content: '' + value: '' } this.handleChange = this.handleChange.bind(this) @@ -17,10 +17,15 @@ class Index extends PureComponent { handleChange(event) { const { value } = event.target - + const input = this.handler.input + const idx = input.selectionStart + const caretPosition = () => { + input.selectionStart = input.selectionEnd = idx + } + this.setState({ value: toTitle(value) - }) + }, caretPosition) event.preventDefault() }