Skip to content

Instantly share code, notes, and snippets.

@iremlopsum
Last active September 22, 2017 12:31
Show Gist options
  • Save iremlopsum/a63164302dc8b9a3b58526298b54d5e9 to your computer and use it in GitHub Desktop.
Save iremlopsum/a63164302dc8b9a3b58526298b54d5e9 to your computer and use it in GitHub Desktop.
import React, { PureComponent } from 'react'
import { View, TextInput, StyleSheet, Platform } from 'react-native';
class ExpandingTextInput extends PureComponent {
constructor(props) {
super(props)
this.state = {}
this.onContentSizeChange = this.onContentSizeChange.bind(this);
}
componentWillMount() {
let { style } = this.props;
if (StyleSheet.flatten(style).lineHeight) {
this.setState({ lineHeight: StyleSheet.flatten(style).lineHeight, inputHeight: StyleSheet.flatten(style).lineHeight})
}
}
componentWillUnmount() {
clearTimeout(this._contentTimer);
}
getInputSize() {
let { minRows, maxRows } = this.props;
let { inputHeight, lineHeight } = this.state;
let current = Math.round((inputHeight / lineHeight));
return Math.min(Math.max(minRows, current), maxRows);
}
onContentSizeChange(e) {
let { inputHeight } = this.state;
// Home made debouncer
clearTimeout(this._contentTimer);
if (inputHeight !== e.nativeEvent.contentSize.height) {
let height = e.nativeEvent.contentSize.height;
this._contentTimer = setTimeout(() => {
this.setState({ inputHeight: Math.round(height) })
}, 50);
}
}
render() {
let { style, children, ...rest } = this.props;
let { lineHeight } = this.state;
let lineNumbers = this.getInputSize();
let iOSInputHeight = Platform.OS === 'ios' ? { height: (this.getInputSize() * lineHeight) } : {};
return (
<TextInput
numberOfLines={lineNumbers}
multiline={true}
style={[style, iOSInputHeight]}
onContentSizeChange={this.onContentSizeChange}
{...rest}
>
{children}
</TextInput>
)
}
}
export default ExpandingTextInput
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment