Skip to content

Instantly share code, notes, and snippets.

@thebigredgeek
Created December 1, 2016 20:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thebigredgeek/a9bb9d48d300f69ecd332f24d2a3b2ab to your computer and use it in GitHub Desktop.
Save thebigredgeek/a9bb9d48d300f69ecd332f24d2a3b2ab to your computer and use it in GitHub Desktop.
Pure input component with external value and sticky cursor
import React, { PropTypes } from 'react';
import classNames from 'classnames';
import { autobind } from 'core-decorators'
import PureComponent from './pure';
@withStyles(style)
export default class Input extends PureComponent {
static propTypes = {
onChange: PropTypes.func.isRequired,
value: PropTypes.any.isRequired,
className: PropTypes.string,
focus: PropTypes.any,
placeholder: PropTypes.string
}
static defaultProps = {
onChange: d => d,
value: '',
className: '',
focus: undefined,
placeholder: ''
}
constructor (props, context) {
super(props, context);
this.state = {
curPos: (props.value || '').length
};
}
componentDidMount () {
if (this.props.focus !== undefined) this.refs.input.focus();
}
componentDidUpdate () {
this.refs.input.setSelectionRange(this.state.curPos, this.state.curPos);
}
@autobind
_onChange (e) {
e.preventDefault();
const curPos = e.target.selectionEnd;
const val = e.target.value;
this.setState({
curPos
}, () => {
this.props.onChange(val)
});
}
render () {
return (
<input
className={classNames('form-control', this.props.className)}
onChange={this._onChange}
value={this.props.value}
placeholder={this.props.placeholder}
ref='input'
/>
);
}
}
import React, { Component } from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
export default class PureComponent extends Component {
constructor (props, context) {
super(props, context);
this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment