You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When an input element is "controlled" by a model, the cursor will jump to the end of the line on every change. This makes it impossible to edit text that is not at the end of the input.
Your problem is that you're not rerendering with the new value. If you have React rerender with the new input value, then it'll know not to revert the value. (As it is, it will revert to the old value until it gets the new value after 50 ms. Changing 50 to a larger number like 1000 will make this much more apparent.) The following code should work:
varExampleApplication=React.createClass({render: function(){varmodel=this.props.model;return<inputonChange={this.nameChange}value={model.name}/>;},nameChange: function(evt){this.props.model.name=evt.target.value;rerender();}});varmyModel={name: 'Input is funky'};functionrerender(){React.renderComponent(<ExampleApplicationmodel={myModel}/>,document.getElementById('container'));}setInterval(rerender,50);
(The normal way to do this when making a reusable component is to pass down a callback in props to ask the parent component to rerender.)
Reacted by Gerrie van Wyk, Shadid Chowdhury, Olivier Tassinari, Thomas Collardeau, Gergely Fehérvári, MiklZhdanov and Andrzej Dąbrowski
I came across this problem when writing a Flux application. I updated the local state and dispatched an action to update the store. This local state update caused a re-render which still used the current "old" value in the store and thus changed the DOM and moved the cursor.
This Stack Overflow answer helped me understand what was going on, so I thought I'd reference it here since this was the first result I found on Google, but didn't quite help me understand what was going on.
Reacted by Qwerty (Vítězslav Ackermann Ferko), Pedro H. Santiago, Jingbo Jin, Ruaidhrí Primrose, jakobstasilowicz and Trevor
creditcard.parse(*).formatted simply turns a number like 4444555566667777 into a card number like 4444 5555 6666 7777
If I remove call to creditcard.parse(*).formatted and just pass this.state.cardNumber the cursor doesn't jump. But the cursor still jumps even if I pass this.state.cardNumber + '5'; as the next value, so it seems any modification of the string between renders means middle edits (edits before modification point in string) cause cursor to jump to end.
Reacted by Michael Zedeler, Chet Corcos, Shergin Rodion, Kevin, Ethan Resnick, Kevin Ross, Sean Miller, Aleksey Gurtovoy, Jonathan Leung, Jeppe Jernberg and 8 more
@tsheaff@mikeljames The problem is that React doesn't have enough information to do something intelligent. Assuming ^ represents the cursor, suppose the input looks like
401^8 8888 8881 881
(that is, between "1" and "8" in "4018"). Then I type a "2". Momentarily, the input looks like
4012^8 8888 8881 881
but immediately, creditcard.parse(*).formatted returns
4012 8888 8888 1881
Where should the cursor go? Even as a human looking at this, it's unclear: it could go before or after the space:
4012^ 8888 8888 1881
4012 ^8888 8888 1881
Figuring this out programmatically seems impossible to me in the general case. Even if we were content to return either of those, it's hard for me to imagine an algorithm that might work reliably. Let me know if I'm missing something.
Because this is impossible and requires more knowledge about the specific problem space, React doesn't attempt to do anything intelligent with the cursor; you can set .selectionStart/.selectionEnd manually as appropriate for your domain. In the case of filtering out some characters it would be possible to write a more general solution but I think that may still be better left to a third-party component.
Reacted by Eric Eastwood, Chakrit Likitkhajorn, Harrison Mendonça, Stanley Sathler, David Vogeleer, Jeppe Jernberg, Yauheni Prakopchyk, Huey, kp (Khoa), Peter Hozák and 1 more
You can almost certainly do better than jumping to the end for your specific case of formatting using some simple heuristic. Doesn't make sense for React to burn extra cycles attempting to do this in general (e.g. formatting could be additive or subtractive).
Perhaps linking this issue or a related discussion could be helpful in the official docs as I'd imagine formatting (phone numbers, credit cards, SSNs) is quite common.
Actually: Stripe's jQuery.payment library preserves cursor position except if your cursor is already at the end, in which case it keeps your cursor at the end of the input. This generally feels pretty reasonable; try:
That example flickers but that's not inherent to the strategy so we could do better. This might be more predictable in the common case, at the expense of introducing edge-case bugs because you now don't need to think about what should happen. For example, this strategy does feel broken in the case that you're typing before a space. If you have:
4018^ 8888 8881 881
and type a 7 you have
40187^ 8888 8881 881
which gets changed to
4018 ^7888 8888 1881
which feels wrong because your cursor should be after the 7, not before. But maybe this behavior is still better.
Wait: this wouldn't work at all for filtering out chars because your cursor would move over whenever you type an invalid character. Maintaining the distance from the end might work though?
The numbers input works great. For the CC input: If you type "1234 5678" and then try to type a character after the space, your cursor is in the wrong place. Similarly, typing "1234 567" and then typing a character before the space does the wrong thing.
Reacted by Ziad El Khoury Hanna, Bart Mosley, April Johnson, Tiberiu Popescu, Jeremy Kahn, マーティン V, Anton Novik and Amnon Sadeh
I don't know if this is still relevant, but I was able to solve this issue by just keeping track of the carat position and updating it when necessary.
Note: This may or may not compile as-is. I pasted it from a more complex Component and whittled it down to the [mostly] bare essentials to show how it works.
import React from 'react';
class Input extends React.Component {
static defaultProps = {
shouldCommitValue: value => true
}
constructor(props) {
super(props);
this.inputRef = React.createRef();
this.state = {
value: '',
inputSelection: false,
updateSelection: false
};
}
render() {
const otherProps = {shouldCommitValue, onFocus, onKeyDown, onChange, ...otherProps} = this.props;
this.onFocus = onFocus;
this.onChange = onChange;
this.onKeyDown = onKeyDown;
return (
<input
ref={this.inputRef}
value={this.state.value}
onFocus={this.handleInputFocus}
onKeyDown={this.handleInputKeyDown}
onChange={this.handleInputChange}
{...otherProps}
/>
);
}
handleInputFocus = (...args) => {
// Save the initial cursor position when the user focuses the input.
this.saveCursorPosition();
if (this.onFocus instanceof Function) {
this.onFocus(...args);
}
}
handleInputKeyDown = (...args) => {
// Save the updated cursor position as the user interacts with the input.
this.saveCursorPosition();
if (this.onFocus instanceof Function) {
this.onKeyDown(...args);
}
}
handleInputChange = (event, ...otherArgs) => {
const value = event.target.value;
if (this.props.shouldCommitValue(value)) {
// The value should be committed, business as usual...
this.setState({ value });
} else {
// The value was ignored (or altered).
// Since DOM input element's input state and the value used during the re-render will be different,
// the input field will be out of sync and the result is the cursor will jump to the end.
// ...so signal to componentDidUpdate() that we want to update the selection afterwards!
this.setState({
updateSelection: { ...this.state.inputSelection }
});
}
if (this.onChange instanceof Function) {
this.onChange(event, ...otherArgs);
}
}
componentDidUpdate() {
// If there was a request to update the selection via setState...
if (this.state.updateSelection) {
// Update the selection.
const selection = this.state.updateSelection;
this.inputRef.current.selectionStart = selection.start;
this.inputRef.current.selectionEnd = selection.end;
// Important! Clear out the update request, otherwise you will end up with an infinite loop.
this.setState({updateSelection: false});
}
}
saveCursorPosition = () => {
this.setState({
inputSelection: {
start: this.inputRef.current.selectionStart,
end: this.inputRef.current.selectionEnd
}
});
}
}
This is an example of just disallowing certain types of strings to bet set as the value. For example, to limit the input to valid CSS selectors:
What do you think about this guys ?
I realized that It can be managed by using React Refs but it is necessary to use a Statefull Component because you need to use the callback function after have been updated the state.
for me, cursor jumping started when I refactored from componentWillReceiveProps to static getDerivedStateFromProps, but does NOT happen with getDerivedStateFromProps that isn't static
could it be a babel/webpack problem?
(reproducible with React 16.4, react-autosuggest 9.4.2, react-scripts 1.1.5)
edit: sorry, without static it just doesn't do anything so the cursor won't jump but it's not a workaround, I will keep using good old (== working) componentWillReceiveProps until there is something better that works.
I don't see why you would use state here. This is not data that should cause your component to re-render. You just want to update the selection on your ref.
Does anyone have any ideas for dealing with this on an input with type="email"? The problem is selectionStart, selectionEnd and setSelectionRange are not available for this input type. I thought about changing type to text before getting and updating the selection, but this isn't really practical because it would have to run through multiple renders to change the type and then get the selection range. Even then, it's not really feasible because the type needs to be changed back to email and would require another setState in componentDidUpdate, which is ugly. I even wonder if this will cause problems with iOS keyboard types due to the switch between email and text while the user is typing.
For anyone else looking for a solution, instead of changing type only during setSelection, I ended up switching to a text type input on focus and back to original input type on blur. I don't think this is an ideal solution, but it works, and I don't see any major problems with it. I would be happy to be able to remove these parts of my component if this issue is ever addressed because it adds a lot of complexity.
If anyone is still facing this problem, the easiest way is to preserve the cursor position before updating state and use the cursor position AFTER updating the state (not through callback)
onChange={(event) => {
const caretStart = event.target.selectionStart;
const caretEnd = event.target.selectionEnd;
// update the state and reset the caret
this.updateState();
event.target.setSelectionRange(caretStart, caretEnd);
}}
@dhiraj1site I had to add event.persist() for the code to work.
onChange={(event)=>{event.persist()constcaretStart=event.target.selectionStart;constcaretEnd=event.target.selectionEnd;// update the state and reset the caretthis.updateState();event.target.setSelectionRange(caretStart,caretEnd);}}
I'm going to lock because a lot of new solutions in this thread look suspicious and likely point to other misunderstandings or bugs.
The canonical solution is to make sure you're calling setState with e.target.value during the onChange event. That should be enough to preserve the cursor.
If it's not enough for you, please file a new issue with your reproducing case.
Activity
sophiebits commentedon Jan 23, 2014
Your problem is that you're not rerendering with the new value. If you have React rerender with the new input value, then it'll know not to revert the value. (As it is, it will revert to the old value until it gets the new value after 50 ms. Changing 50 to a larger number like 1000 will make this much more apparent.) The following code should work:
(The normal way to do this when making a reusable component is to pass down a callback in
propsto ask the parent component to rerender.)ericvicenti commentedon Jan 23, 2014
Ah, thanks for the help!
I'm not a big fan of passing a callback down, so I'm going to try and re-render from the parent immediately on model change events.
sophiebits commentedon Jan 23, 2014
Great -- that should work too.
Fix issue with jumping cursor in controlled input fields.
marnusw commentedon May 14, 2015
I came across this problem when writing a Flux application. I updated the local state and dispatched an action to update the store. This local state update caused a re-render which still used the current "old" value in the store and thus changed the DOM and moved the cursor.
This Stack Overflow answer helped me understand what was going on, so I thought I'd reference it here since this was the first result I found on Google, but didn't quite help me understand what was going on.
tsheaff commentedon Oct 23, 2015
@spicyj I'm seeing a similar issue of the cursor jumping to the end whenever I format / modify a controlled input's value between renders.
Here's my code:
creditcard.parse(*).formattedsimply turns a number like4444555566667777into a card number like4444 5555 6666 7777If I remove call to
creditcard.parse(*).formattedand just passthis.state.cardNumberthe cursor doesn't jump. But the cursor still jumps even if I passthis.state.cardNumber + '5';as the next value, so it seems any modification of the string between renders means middle edits (edits before modification point in string) cause cursor to jump to end.I'm on
[email protected]export-mike commentedon Nov 30, 2015
@tsheaff did you find a solution to this in the end? I'm also doing some onChange formatting to my text field.
sophiebits commentedon Nov 30, 2015
@tsheaff @mikeljames The problem is that React doesn't have enough information to do something intelligent. Assuming
^represents the cursor, suppose the input looks like(that is, between "1" and "8" in "4018"). Then I type a "2". Momentarily, the input looks like
but immediately,
creditcard.parse(*).formattedreturnsWhere should the cursor go? Even as a human looking at this, it's unclear: it could go before or after the space:
Figuring this out programmatically seems impossible to me in the general case. Even if we were content to return either of those, it's hard for me to imagine an algorithm that might work reliably. Let me know if I'm missing something.
Because this is impossible and requires more knowledge about the specific problem space, React doesn't attempt to do anything intelligent with the cursor; you can set .selectionStart/.selectionEnd manually as appropriate for your domain. In the case of filtering out some characters it would be possible to write a more general solution but I think that may still be better left to a third-party component.
tsheaff commentedon Nov 30, 2015
Yes @mikeljames it's impossible in general as @spicyj explains.
You can almost certainly do better than jumping to the end for your specific case of formatting using some simple heuristic. Doesn't make sense for React to burn extra cycles attempting to do this in general (e.g. formatting could be additive or subtractive).
Perhaps linking this issue or a related discussion could be helpful in the official docs as I'd imagine formatting (phone numbers, credit cards, SSNs) is quite common.
sophiebits commentedon Dec 1, 2015
Actually: Stripe's jQuery.payment library preserves cursor position except if your cursor is already at the end, in which case it keeps your cursor at the end of the input. This generally feels pretty reasonable; try:
http://stripe.github.io/jquery.payment/example/
That example flickers but that's not inherent to the strategy so we could do better. This might be more predictable in the common case, at the expense of introducing edge-case bugs because you now don't need to think about what should happen. For example, this strategy does feel broken in the case that you're typing before a space. If you have:
and type a 7 you have
which gets changed to
which feels wrong because your cursor should be after the 7, not before. But maybe this behavior is still better.
cc @zpao for a second opinion.
sophiebits commentedon Dec 1, 2015
That is: I'm entertaining the idea of React's
<input>doing this by default.sophiebits commentedon Dec 1, 2015
Wait: this wouldn't work at all for filtering out chars because your cursor would move over whenever you type an invalid character. Maintaining the distance from the end might work though?
sophiebits commentedon Dec 1, 2015
Here you can try it:
http://jsbin.com/dunutajuqo/edit?js,output
The numbers input works great. For the CC input: If you type "1234 5678" and then try to type a character after the space, your cursor is in the wrong place. Similarly, typing "1234 567" and then typing a character before the space does the wrong thing.
32 remaining items
amirouche commentedon Jul 15, 2018
It's slowing down development time 👎
amirouche commentedon Jul 15, 2018
I will try ant design kit to see if the issue is present.
nerdo commentedon Aug 8, 2018
I don't know if this is still relevant, but I was able to solve this issue by just keeping track of the carat position and updating it when necessary.
Note: This may or may not compile as-is. I pasted it from a more complex Component and whittled it down to the [mostly] bare essentials to show how it works.
This is an example of just disallowing certain types of strings to bet set as the value. For example, to limit the input to valid CSS selectors:
juan-ee commentedon Aug 16, 2018
What do you think about this guys ?
I realized that It can be managed by using React Refs but it is necessary to use a Statefull Component because you need to use the callback function after have been updated the state.
paul-cheung commentedon Sep 10, 2018
@nerdo thanks, it helped.
Aprillion commentedon Oct 1, 2018
for me, cursor jumping started when I refactored from
componentWillReceivePropstostatic getDerivedStateFromProps, but does NOT happen withgetDerivedStateFromPropsthat isn'tstaticcould it be a babel/webpack problem?
(reproducible with React 16.4, react-autosuggest 9.4.2, react-scripts 1.1.5)
edit: sorry, without
staticit just doesn't do anything so the cursor won't jump but it's not a workaround, I will keep using good old (== working)componentWillReceivePropsuntil there is something better that works.ahce commentedon Oct 21, 2018
Hi! this is my solution https://codesandbox.io/s/9208ol4r8y
emkayy commentedon Nov 1, 2018
I don't see why you would use state here. This is not data that should cause your component to re-render. You just want to update the selection on your ref.
I implemented it like this:
Quick and simple. Works perfectly fine for me.
binomialstew commentedon Nov 5, 2018
Does anyone have any ideas for dealing with this on an input with type="email"? The problem is
selectionStart,selectionEndandsetSelectionRangeare not available for this input type. I thought about changing type to text before getting and updating the selection, but this isn't really practical because it would have to run through multiple renders to change the type and then get the selection range. Even then, it's not really feasible because the type needs to be changed back to email and would require anothersetStateincomponentDidUpdate, which is ugly. I even wonder if this will cause problems with iOS keyboard types due to the switch between email and text while the user is typing.binomialstew commentedon Nov 8, 2018
For anyone else looking for a solution, instead of changing type only during
setSelection, I ended up switching to atexttype input onfocusand back to original inputtypeonblur. I don't think this is an ideal solution, but it works, and I don't see any major problems with it. I would be happy to be able to remove these parts of my component if this issue is ever addressed because it adds a lot of complexity.dhiraj1site commentedon Dec 14, 2018
If anyone is still facing this problem, the easiest way is to preserve the cursor position before updating state and use the cursor position AFTER updating the state (not through callback)
ahuglajbclajep commentedon Jan 14, 2019
Probably the smallest complete example with TypeScript:
taniarascia commentedon Mar 4, 2019
@dhiraj1site I had to add
event.persist()for the code to work.gaearon commentedon Mar 4, 2019
I'm going to lock because a lot of new solutions in this thread look suspicious and likely point to other misunderstandings or bugs.
The canonical solution is to make sure you're calling
setStatewithe.target.valueduring theonChangeevent. That should be enough to preserve the cursor.If it's not enough for you, please file a new issue with your reproducing case.