gcanti / tcomb-form

Forms library for react
https://gcanti.github.io/tcomb-form
MIT License
1.16k stars 136 forks source link

How to build a autosize textarea custom factory #274

Open gcanti opened 8 years ago

gcanti commented 8 years ago

Another example of a custom factory: an autosize textarea using @buildo's react-autosize-textarea

import classnames from 'classnames'
import ReactAutosizeTextarea from 'react-autosize-textarea'

// override just the renderTextarea partial of the default template
function renderTextarea(locals) {
  const attrs = {
    ...locals.attrs,
    className: classnames(locals.attrs.className)
  }
  const onChange = (evt) => locals.onChange(evt.target.value)
  return <ReactAutosizeTextarea rows="3" {...attrs} value={locals.value} onChange={onChange} />
}

const textboxTemplate = t.form.Form.templates.textbox.clone({ renderTextarea })

// here we are: the factory
class AutosizeTextareaFactory extends t.form.Textbox {

  getTemplate() {
    return textboxTemplate
  }

}

// example
const Type = t.struct({
  text: t.String
})

const options = {
  fields: {
    text: {
      type: 'textarea',
      factory: AutosizeTextareaFactory
    }
  }
}