UNPKG

phoenix-components-library

Version:

Component library for Phoenix Frontend Projects.

129 lines (105 loc) 2.82 kB
import React, { Component } from "react"; import PropTypes from "prop-types"; import "./Input.css"; class Input extends Component { static propTypes = { name: PropTypes.string, type: PropTypes.string, value: PropTypes.string, class: PropTypes.string, color: PropTypes.string, placeholder: PropTypes.string, onChangeInput: PropTypes.func, onFocusInput: PropTypes.func }; static defaultProps = { name: "", type: "text", value: "", placeholder: "", class: "", color: "", onChangeInput: () => {}, onFocusInput: () => {} }; state = { inputInFocus: false, inputValue: this.props.value }; labelClasses = { emptyField: "es-label", fieldInFocus: "es-input-label", fullField: "es-label-full" }; greyBackgroundLabelClasses = { emptyField: "es-label grey", fieldInFocus: "es-input-label grey", fullField: "es-label-full grey" }; static getDerivedStateFromProps = nextProps => ({ inputValue: nextProps.value }); focusHandler = e => { e.preventDefault(); this.setState({ inputInFocus: true }); this.props.onFocusInput(e); }; blurHandler = e => { e.preventDefault(); this.setState({ inputInFocus: false }); }; onInputValueChangeHandler = e => { e.preventDefault(); this.setState({ inputValue: e.target.value }); this.props.onChangeInput(e); }; getLabelClass = () => { if (this.props.color === "grey") { return this.getSerachLabelClass(); } return this.getInputLabelClass(); }; getInputLabelClass = () => { if (this.isInputFieldInFocus()) { return this.labelClasses.fieldInFocus; } return this.isInputFieldEmpty() ? this.labelClasses.emptyField : this.labelClasses.fullField; }; getSerachLabelClass = () => { if (this.isInputFieldInFocus()) { return this.greyBackgroundLabelClasses.fieldInFocus; } return this.isInputFieldEmpty() ? this.greyBackgroundLabelClasses.emptyField : this.greyBackgroundLabelClasses.fullField; }; isInputFieldEmpty = () => this.state.inputValue.length === 0; isInputFieldInFocus = () => this.state.inputInFocus; render() { return ( <div className={`es-input ${this.props.class}`}> <input type={this.props.type} name={this.props.name} value={this.state.inputValue} onChange={this.onInputValueChangeHandler} onFocus={this.focusHandler} onBlur={this.blurHandler} disabled={this.props.disabled ? "disabled" : ""} /> <label className={this.getLabelClass()} htmlFor="search-field"> {this.props.placeholder || this.props.name} </label> </div> ); } } export { Input };