Skip to content

Instantly share code, notes, and snippets.

@xionon
Created February 20, 2015 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xionon/d0e0ce2535c8724b058b to your computer and use it in GitHub Desktop.
Save xionon/d0e0ce2535c8724b058b to your computer and use it in GitHub Desktop.
rails jsx helper
var RailsForm = React.createClass({
propTypes: {
csrf: React.PropTypes.shape({
param: React.PropTypes.string,
token: React.PropTypes.string
}).isRequired
},
getDefaultProps: function() {
return {
method: "post"
}
},
render: function() {
return (
<form acceptCharset="UTF-8" { ...this.props } method="post" >
<input type="hidden" name="_method" value={this.props.method} />
<input type="hidden" name={this.props.csrf.param} value={this.props.csrf.token} />
{this.props.children}
</form>
);
}
})
@xionon
Copy link
Author

xionon commented Feb 20, 2015

This class will help you generate forms valid for Rails. You will need to pass your CSRF param & token in as a property, so that Rails can validate the request. If you are using Jbuilder, just add this to the .json.jbuilder template that you pass into react_component:

json.csrf do
  json.token form_authenticity_token
  json.param "authenticity_token"
end

You can use the element like so:

<RailsForm csrf={this.csrfToken} method="PUT">
  <label><span>Email address</span><input type="text" name="user[email]" /></label>
  <input type="submit" />
</RailsForm>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment