Textarea Component

by nathanlogan

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://npmcdn.com/react@latest/dist/react-with-addons.js"></script>
<script src="https://npmcdn.com/react-dom@latest/dist/react-dom.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>

<div id="container"></div>

CSS

body {padding: 10px; background: #fff;}
.hw-textarea {display:block; padding:10px; border: 1px solid #c00; margin-bottom:10px; background: linear-gradient(#fcfcfc, #ddd);}
textarea {width:92%; margin: 2%; padding: 2%;}
.hw-textarea-label {font-weight: bold; font-family: Arial;}
p.hw-textarea-textarea {color: green;}

JavaScript 1.7

var Textarea = React.createClass({

  onFocus: function (e) {
    // this.props.onFocus(e)
  },

  onBlur: function (e) {
    // this.props.onBlur(e)
  },

  onKeyDown: function (e) {
    // per specs: "Text box does not exceed 250 characters. If user types more characters than the limit, they will not appear in the text field."
    if (
      // self-explanatory
      this.props.maxCharacters !== null &&
      e.target.value.length >= parseInt(this.props.max) &&
      // don't block the delete key
      e.keyCode !== 8
    ) {
      e.preventDefault()
      e.stopPropagation()
    }

    // this.props.onKeyDown(e)
  },

  onChange: function (e) {
  	if (this.props.onChange) {
    	this.props.onChange(e);
    }
  },

  render: function () {
    let {
      id,
      name,
      value,
      label,
      max,
      readonly } = this.props

    let charLimit = ''
    if (max) {
      // potentially destructive, but part of requirements (see comment above)
      if (value) {
        value = value.substring(0, max)
      }

      charLimit = <div className={'hw-textarea-counter'}>{max} character limit</div>
    }

    let textarea = (
      <span className="">
        <textarea
          className={'hw-textarea-textarea'}
          id={id}
          name={name}
          defaultValue={value}
          onFocus={this.onFocus}
          onBlur={this.onBlur}
          onKeyDown={this.onKeyDown}
          onChange={this.onChange}
        />
        {charLimit}
      </span>
    )

    if (readonly) {
      textarea = (
        <p className='hw-textarea-textarea'>{value}</p>
      )
    }

    return (
      <label className='hw-textarea'>
        <div className='hw-textarea-label'>
          {label}
        </div>
        {textarea}
      </label>
    )
  }

});




var onChange = function (e) {
  changeRecord = e.target.value
  
  ReactDOM.render(
  	<Textarea label="Text:" value={changeRecord} readonly={true} />,
  	document.getElementById('placeholder')
	);
}

var...