score:40

Accepted answer

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.

score:1

You can render your form inside an invisible block and then clone it into a react component

/* app/assets/stylesheets/users.scss */
.invisible-form-container {
  display: none;
}
# app/views/users/edit.html.haml
.invisible-form-container
  = render 'form'
.react-container
# app/assets/javascripts/components/form.js.jsx.coffee
class @Form extends React.Component
  html_form: ->
    {__html: $('.invisible-form-container').html()}
  render: ->
    `<div dangerouslySetInnerHTML={this.html_form()} />`
# app/assets/javascripts/initializer.coffee
$ ->
  ReactDOM.render(
    `<Form />`,
    $('.react-container')[0]
  )

Hope this helps.

score:8

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>
    );
  }
});

score:13

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.


Related Query

More Query from same tag