Skip to content

Instantly share code, notes, and snippets.

@iain-merrick-fanduel
Created March 27, 2020 12:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iain-merrick-fanduel/b9cea57baa9f20a5d288a0fcd6e7ee5e to your computer and use it in GitHub Desktop.
Save iain-merrick-fanduel/b9cea57baa9f20a5d288a0fcd6e7ee5e to your computer and use it in GitHub Desktop.
Bug: cursor jumps to end of controlled <input> tag when value is modified
// Adapted from example code in https://reactjs.org/docs/forms.html
// Original CodePen link: https://codepen.io/gaearon/pen/VmmPgp?editors=0010
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: 'put_a_space_in_the_middle'};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value.replace(/ /g, '_')});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<p>The &lt;input&gt; component below now converts spaces to underscores.</p>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
<p>BUG: if you add a space in the middle of the input, the cursor jumps to the end.</p>
</form>
);
}
}
ReactDOM.render(
<NameForm />,
document.getElementById('root')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment