yerassyl yerassyl - 1 year ago 296
HTML Question

How to create forms with React and Rails?

With Rails I create forms using the form_for tag.

Rails generates the HTML form automatically, including the authenticity_token for security against Cross-Site Request Forgery (CSRF).

With React I use JSX, so I cannot render erb in a React component.

In a React component I write HTML manually.

I want to use React in my Rails app and still have the advantages of Rails.

Or if there is no way to get the Rails advantages of form_for when using React as V of my app, how can i write proper form in React component?

If I will firstly write my form_for and then look at rendered html copy it and paste into my React component, is that a good idea?

For example here is rendered html from form_for:

<form class="new_user" id="new_user" action="/users" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="authenticity_token" value="1AXH9blzaH4qEAAWTvu6aAH84btA/9DZCpFDBhiJ0/H9uAKsPAB/rFQWY1VmWA1yNtFaigO50p6joa3X8CItBA==" />

<div class="field">
<label for="user_Имя">Имя</label><br>
<input placeholder="Бил Гейтс" type="text" name="user[name]" id="user_name" />

<div class="actions">
<input type="submit" name="commit" value="Открыть заявку" class="button tiny" />



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} />

It's not the best solution. I would be happy if someone will tell a better solution.