Skip to content

Instantly share code, notes, and snippets.

@savelichalex
Last active May 10, 2017 14:15
Show Gist options
  • Select an option

  • Save savelichalex/0cdd767e3adb3bbbab80671a26af61d8 to your computer and use it in GitHub Desktop.

Select an option

Save savelichalex/0cdd767e3adb3bbbab80671a26af61d8 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
class Input extends Component {
static state = {
curPos: null,
}
componentDidUpdate() {
const {
curPos,
} = this.state;
if (curPos) {
this.setCarretPosition(curPos);
}
}
setCarretPosition(position) {
const field = this.inputComp;
if (field == null || position == null) {
return;
}
if ('selectionStart' in field && 'selectionEnd' in field) {
field.selectionStart = position;
field.selectionEnd = position;
} else { // IE
if (field.createTextRange == null) {
return;
}
const range = field.createTextRange();
range.collapse(true);
range.moveStart('character', position);
range.moveEnd('character', position);
range.select();
}
}
onChange = (event) => {
if (this.inputComp != null) {
this.setState({
curPos: Input.getSelectionEnd(event, this.inputComp),
});
}
this.props.onChange(event);
}
render() {
return <input value={this.props.value} onChange={this.onChange} />
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment