How to create forms with React and Rails?
You can paste authenticity_token
into react component.
Using gem react-rails
= react_component 'Form', authenticity_token: form_authenticity_token
form_authenticity_token
is the rails helper.
So you can paste it into your form.
<form role='form' accept-charset="UTF-8" action='/action' method='post'> ... <input type='hidden' name='authenticity_token' value={this.props.authenticity_token} /> ...</form>
It's not the best solution. I would be happy if someone will tell a better solution.
You can do something like this:
$(document).ready(function(){ $.ajaxSetup({ headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') } });});
and put the csrf-token
into a meta tag inside your view/layout if it isn't already there.
If you render the base HTML with Rails and embed a React component to it with react-rails
, you can write like this:
var YourForm = React.createClass({ render: function() { var csrfToken = $('meta[name=csrf-token]').attr('content'); return ( <form action='/users' method='post' accept-charset='UTF-8'> <input type='hidden' name='_method' value='patch' /> <input type='hidden' name='utf8' value='✓' /> <input type='hidden' name='authenticity_token' value={csrfToken} /> ... </form> ); }});