UNPKG

svf

Version:

A simple validate form and React-based implementation

67 lines (61 loc) 1.87 kB
import React, { Component } from "react"; class Input extends React.Component { static defaultProps = { type: "text", placeholder: "" }; constructor (props) { super(props); const { name } = props; this.state = { [name]: "" }; } componentWillReceiveProps (nextProps) { const { name } = this.props; const prevValue = this.props[name], nextValue = nextProps[name]; if (prevValue !== nextValue) { this.setState({ [name]: nextValue }); } } componentDidMount () { const { name, rules = [] } = this.props; this.props.updateRules({ [name]: rules }); } handleInputChange (type, e) { this.props.updateState({ [type]: e.target.value }); } render () { const { label, required, name, type, placeholder, totalErrors } = this.props; const value = this.state[name]; const error = totalErrors[name]; const hasError = !!error, message = (hasError && error.message) || ""; return ( <div> { label ? ( <div className="label"> <label className={ required ? "required" : "" }> { label } </label> </div> ) : "" } <span className={ "input-wrapper" + (hasError ? " error": "")}> <input className="input input-lg" value={ value } type={ type } onChange={ this.handleInputChange.bind(this, name) } placeholder={ placeholder } /> </span> { message ? ( <div className="explain">{ message }</div> ) : "" } </div> ) } } export default Input;