Build forms that will be submitted to Rails in React.
npm install react-rails-form-helpersUsing via npm
```
npm install --save react-rails-form-helpers
Usage via vendoring
You can grab the latest UMD build from https://unpkg.com/react-rails-form-helpers@latest/dist/react-rails-form-helpers.js
This package provides components for composing a form targeted at Rails.
The main intent of this package is for communicating the intent of the form via named components.
If you're scared by Rails Magic you'll be happy to know that these components are mostly dumb.
The only magical parts are generating the attribute names and ensuring that the fields Rails expects exist on a form.
There are two varieties of components.
The components with a Tag suffix are not magical at all.
They exist to mirror the [Rails form helpers][] for expressing the intent.
They are tiny wrappers around the built in ReactDOM and components.
The components without a Tag suffix are only slightly magical.input[name]
They use a React context to generate the and label[for] attribute for nested attributes.
The FormTag component is a slim wrapper around the builtin
component.
It does three things:1. Generates the hidden input for Rails' faux
PUT, PATCH, and DELETE requests
2. Generates the hidden input for Rails' csrf_token which MUST be include in the document head
3. Generates the hidden input for Rails' utf8 param to match the convention$3
The
FormFor component is a Higher Order Component (HOC) of the FormTag component.
It provides the Rails context for generating input[name] by using it's own name prop.$3
The
FieldsFor component pushes a name onto the Rails naming context.
That's it.FieldsFor can be used in place of a FormFor if you want to generate the form tag in rails and only render part of the form body using React.FieldsFor is aliased as HashFields and ArrayFields for expressing intent.$3
Let's build an example form with the
FormFor component for generating correctly named field inputs.`jsx
const EditOrderForm = React.createClass({
getInitialState() {
return {
burgers: this.props.burgers,
}
}, handleAddBurger() {
const newBurger = { variety: "Hamburger", add_fried_egg: false }
const burgers = [ ...this.state.burgers, newBurger ]
this.setState({ burgers })
},
handleRemoveBurger(burgerToRemove) {
return () => {
const burgers = this.state.burgers.map((burger) => (
burger === burgerToRemove ? { ...burger, destroy: true } : burger
))
this.setState({ burgers })
}
},
render() {
return (
{this.state.burgers.map((burger, index) => {
{burger.id && (
)}
{burger.destroy ? (
) : (
)}
})}
)
}
})
`The raw HTML output for this form (sanitized for legibility)
`html
``