Skip to content

Instantly share code, notes, and snippets.

@roman01la
Last active November 15, 2016 23:20
Show Gist options
  • Save roman01la/d9e2b7ddd6c73cbf4bf0cf1611003113 to your computer and use it in GitHub Desktop.
Save roman01la/d9e2b7ddd6c73cbf4bf0cf1611003113 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import {
PixelRatio,
View,
TextInput,
Text,
StyleSheet,
PropTypes
} from 'react-native';
var RCTUIManager = require('NativeModules').UIManager;
var AutoExpandingTextInput = React.createClass({
// propTypes: React.TextInput.propTypes,
propTypes: TextInput.propTypes,
getInitialState: function() {
return {
height: 0,
text: ""
};
},
componentDidMount() {
if(this.props.value !== this.state.text) {
this.setState({text:this.props.value});
}
},
componentWillReceiveProps(nextProps){
if(nextProps.value !== this.props.value){
this.setState({text: nextProps.value})
}
},
setNativeProps: function(nativeProps) {
var input = this.refs.input;
var hidden = this.refs.hidden;
input.setNativeProps(nativeProps);
hidden.setNativeProps(nativeProps);
if (nativeProps.text !== undefined) {
this.state.text = nativeProps.text;
}
},
onInputLayout: function(event) {
var width = event.nativeEvent.layout.width;
if (this.state.width !== width) {
this.setState({width: width});
}
},
onHiddenLayout: function(event) {
var height = event.nativeEvent.layout.height;
// if (height < 50) {
// height = 50;
// }
// if (height > 205) {
// height = 205;
// }
if (this.state.height !== height) {
this.setState({height: height});
}
},
onChange: function(event) {
this.setState({text: event.nativeEvent.text});
if (this.props.onChange) this.props.onChange(event);
},
render: function() {
var passedStyle = this.props.style || {};
var containerStyle = {};
var inputStyle = {};
var hiddenStyle = {};
// TODO: these don't work beause they are StyleSheet compiled ones
// if (passedStyle.flex) containerStyle.flex = passedStyle.flex;
// if (passedStyle.width) containerStyle.width = passedStyle.width;
containerStyle.flex = 1;
inputStyle.height = this.state.height;
if (this.state.width) {
hiddenStyle.width = this.state.width;
}
return (
<View style={containerStyle}>
<TextInput
{...this.props}
onChange={this.onChange}
onLayout={this.onInputLayout}
multiline={true}
ref="input"
style={[styles.input, passedStyle, inputStyle]}
/>
<Text
ref="hidden"
onLayout={this.onHiddenLayout}
style={[styles.hidden, passedStyle, hiddenStyle]}
>
{this.state.text}
</Text>
</View>
);
}
})
var styles = StyleSheet.create({
hidden: {
position: 'absolute',
top: 10000, // way off screen
left: 10000, // way off screen
backgroundColor: 'transparent',
borderColor: 'transparent',
color: 'transparent',
}
});
module.exports = AutoExpandingTextInput;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment