import * as React from 'react'; import * as _ from 'lodash'; import * as DefaultStyles from './style'; import * as autosize from 'autosize'; import { ThemeProvider } from 'styled-components'; export namespace AnimatedLabel { export interface Props { placeholder: string; autosize?: boolean; value: string; onValueChange: (e: any) => void; styles?: Styles; floatingLabelAnimation?: any; id?: string; name?: string; } export interface State { float: boolean; focused: boolean; } export interface Styles { FloatingLabel?: any, FloatingInput?: any, TextArea?: any, LabelContainer?: any } } class AnimatedLabel extends React.Component { private node: any; constructor(props: AnimatedLabel.Props, state: AnimatedLabel.State) { super(props); this.state = { float: false, focused: false, }; } focusHandler = () => { this.setState({ float: true, focused: true }); } blurHandler = () => { this.setState({ float: this.props.value !== '', focused: false }); } handleFocus = () => { this.node.focus(); } componentDidMount() { if (this.node && this.props.autosize) { autosize(this.node); } if (this.props.value !== '') { this.setState({ float: true }); } } componentWillReceiveProps(nextProps: AnimatedLabel.Props) { this.setState((prevState: AnimatedLabel.State) => ({ float: nextProps.value !== '' || prevState.focused })); } render() { const Styles = _.merge(DefaultStyles, this.props.styles); return (
{this.props.placeholder} {this.props.autosize ? ( this.node = node} onFocus={this.focusHandler} onBlur={this.blurHandler} value={this.props.value} id={this.props.id && this.props.id + '-textarea'} name={this.props.name && this.props.name + '-textarea'} /> ) : ( this.node = node} onFocus={this.focusHandler} onBlur={this.blurHandler} value={this.props.value} onChange={this.props.onValueChange} id={this.props.id && this.props.id + '-input'} name={this.props.name && this.props.name + '-input'} /> )}
); } } export default AnimatedLabel;