Skip to content

Instantly share code, notes, and snippets.

@grabbou
Created July 17, 2015 11:48
Show Gist options
  • Save grabbou/170a1c66ea866bec620f to your computer and use it in GitHub Desktop.
Save grabbou/170a1c66ea866bec620f to your computer and use it in GitHub Desktop.
import PureRender from '../decorators/pureRender';
import React from 'react-native';
import autobind from 'autobind-decorator';
import {
TextInput,
Text,
View
} from 'react-native';
import style from './input.style';
@PureRender
export default class Input extends React.Component {
/**
* This is on purpose. In this particular case, we do not want
* to keep the input in sync with the passed value as this produces
* flickering due to some race conditions between Objective-C / Javascript.
* In order to keep it blazing fast yet correct, we sync on blur, once
* user finishes editing
*/
state = {
value: this.props.value,
editing: false
};
static propTypes = {
error: React.PropTypes.string,
isLast: React.PropTypes.bool,
onChange: React.PropTypes.func,
password: React.PropTypes.bool,
placeholder: React.PropTypes.string,
value: React.PropTypes.any
}
static defaultProps = {
error: '',
isLast: false,
onChange: function() {},
password: false
}
/**
* Bubbles up native event
*/
@autobind
onFieldChange(event) {
const text = event.nativeEvent.text;
this.setState({editing: true}, _ => {
this.props.onChange(text);
});
}
/**
* When editing finishes, we update the in-component state
* with the current value passed via props.
*/
@autobind
onEndEditing() {
this.setState({
value: this.props.value,
editing: false
});
}
componentWillReceiveProps({value}) {
if (!this.state.editing) {
this.setState({
value
});
}
}
/**
* Dismisses the underlaying textInput
* making the keyboard dissapear. This is just a proxy to NativeMixins
* that are only exposed on built-in React Native components (like TextInput)
*/
blur() {
this.refs.textInput.blur();
}
/**
* Renders actual input
*/
render() {
const value = this.state.value;
return (
<TextInput
{...this.props}
onChange={this.onFieldChange}
onEndEditing={this.onEndEditing}
placeholder={this.props.placeholder.toUpperCase()}
ref='textInput'
secureTextEntry={this.props.password}
style={style.input}
value={value}
/>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment