score:1

import React from 'react';
import { View, TextInput, Animated } from 'react-native';

export class FloatingLabelInput extends React.Component {
  state = {
    isFocused: false,
  }

  componentWillMount() {
    this._animatedLabelValue = new Animated.Value(this.props.value === '' ? 0 : 1);
  }

  handleFocus = () => this.setState({ isFocused: true });
  handleBlur = () => this.setState({ isFocused: false });

  componentDidUpdate() {
    Animated.timing(this._animatedLabelValue, {
      toValue: (this.state.isFocused || this.props.value !== '') ? 1 : 0,
      duration: 200,
    }).start();
  }

  render() {
    const { label, ...props } = this.props; //Here is the text for the label
    const { isFocused } = this.state;
    const labelStyle = {
      position: 'absolute',
      left: 0,
      top: this._animatedLabelValue.interpolate({
        inputRange: [0, 1],
        outputRange: [this.props.labelFontSize*0.67, -this.props.labelFontSize*0.05],
      }),
      fontSize: this._animatedLabelValue.interpolate({
        inputRange: [0, 1],
        outputRange: [this.props.labelFontSize, this.props.labelFontSize*0.7],
      }),
      color: this._animatedLabelValue.interpolate({
        inputRange: [0, 1],
        outputRange: ['#aaa', '#000'],
      }),
      fontWeight: this.props.bold ? 'bold' : 'normal'
    }
    const containerStyle = {
      paddingTop: 18,
      marginTop: 20
    }
    return (
      <View style={{paddingTop: 18}}>
          <Animated.Text>
            {label}
          </Animated.Text>
          <TextInput
            {...props}
            onFocus={this.handleFocus}
            onBlur={this.handleBlur}
          />
      </View>
    )
  }
}

Related Query

More Query from same tag