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 a proper form as a React component?
If I first write my form_for and then look at the 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="✓" /><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> <div class="actions"> <input type="submit" name="commit" value="Открыть заявку" class="button tiny" /> </div> </form>
In React, form data is usually handled by the components. When the data is handled by the components, all the data is stored in the component state. You can control changes by adding event handlers in the onChange attribute and that event handler will be used to update the state of the variable.
There are two ways to use React with Ruby on Rails. The first is to build two separate, standalone apps, with the React app on a different repository and communicating with the backend via an API. This can simply be achieved by creating both apps separately using Create React App and the Rails CLI.
React and Ruby on Rails are two exceptional frameworks that developers use around the world. React enables developing interactive UIs and Rails is a full-stack technology. Using RoR for business logic & backend and React for frontend, your business can create a high-functioning application.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With