React

by Rajesh Dixit

HTML

<div id="app"></div>

CSS

.error {
  border: 1px solid red;
}

React

class MyInput extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
			value: '',
      isValid: true,
      hasFocus: false
    }
  }
  
  onChange(event) {
  	const value = event.target.value;
    const isValid = value.length >= (this.props.minLength || 0)
  	this.setState({ value, isValid })
  }
  
  onClick() {
  	this.setState({ hasFocus: true })
  }
  
  onBlur() {
  	this.setState({ hasFocus: false })
  }
  
  render() {
  	const { isValid, hasFocus } = this.state;
    return (
    <div>
      <input
        type='text'
        className={ isValid || hasFocus ? '' : 'error'}
        onChange={ this.onChange.bind(this) }
        onClick={ this.onClick.bind(this) }
        onBlur={ this.onBlur.bind(this) }
      />
    </div>
    )
  }
}

ReactDOM.render(<MyInput minLength={6} />, document.querySelector("#app"))