Created
December 1, 2016 20:42
-
-
Save thebigredgeek/a9bb9d48d300f69ecd332f24d2a3b2ab to your computer and use it in GitHub Desktop.
Pure input component with external value and sticky cursor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' | |
/> | |
); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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