Skip to content

Instantly share code, notes, and snippets.

@kirpalmakanga
Created July 30, 2018 13:31
Show Gist options
  • Save kirpalmakanga/c550f798bde12aeb3aa510dd4f293f11 to your computer and use it in GitHub Desktop.
Save kirpalmakanga/c550f798bde12aeb3aa510dd4f293f11 to your computer and use it in GitHub Desktop.
Floating Label Input (React Native) (WIP)
import React, { Component } from 'react';
import { View, TextInput, Animated } from 'react-native';
import Icon from '../Icon';
export default class FloatingLabelInput extends Component {
state = {
isFocused: false
};
componentWillMount() {
this._animatedIsFocused = new Animated.Value(
this.props.value === '' ? 0 : 1
);
}
componentDidUpdate() {
Animated.timing(this._animatedIsFocused, {
toValue: this.state.isFocused || this.props.value !== '' ? 1 : 0,
duration: 200
}).start();
}
handleFocus = () => this.setState({ isFocused: true });
handleBlur = () => this.setState({ isFocused: false });
render() {
const {
label,
icon,
iconSize = { width: (iconWidth = 24), height: (iconHeight = 24) },
...props
} = this.props;
const inputPaddingTop = 18;
const iconPadding = 44;
const labelFontSize = props.style.fontSize || 20;
const labelStyle = label
? {
position: 'absolute',
left: this._animatedIsFocused.interpolate({
inputRange: [0, 1],
outputRange: [iconPadding, 0]
}),
top: this._animatedIsFocused.interpolate({
inputRange: [0, 1],
outputRange: [inputPaddingTop, 0]
}),
fontSize: this._animatedIsFocused.interpolate({
inputRange: [0, 1],
outputRange: [labelFontSize, 14]
}),
color: this._animatedIsFocused.interpolate({
inputRange: [0, 1],
outputRange: [props.style.color, '#000']
})
}
: null;
const iconStyle = {
position: 'absolute',
top: inputPaddingTop,
left: 10,
zIndex: 1
};
return (
<View style={{ paddingTop: inputPaddingTop }}>
{label ? (
<Animated.Text style={labelStyle}>{label}</Animated.Text>
) : null}
<TextInput
{...props}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
inlineImagePadding={icon ? iconPadding : 0}
blurOnSubmit
/>
{icon ? (
<Icon
name={icon}
style={iconStyle}
width={iconWidth}
height={iconHeight}
fill={props.style.color || '#000000'}
/>
) : null}
</View>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment