How can i use Nested forms in ReactJS?

1.2k views Asked by At

Consider this code snnipet:

<%= form_for @survey do |f| %>
  <%= f.error_messages %>
 <p>
   <%= f.label :name %><br />
   <%= f.text_field :name %>
 </p>
  <%= f.fields_for :questions do |builder| %>
    <%= render "question_fields", :f => builder %>
  <% end %>
 <p><%= f.submit "Submit" %></p>
<% end %>

it'll return me has some hash (rails dev would know that). My question is how can i make this format in ReactJS? To receive exact same params as default done by Rails. As for now i can only use HTML tag in JSX. Currently i receive params in controller and sort them according to needs( which seems bad approach). I've tested out some of the npm packages but their docs doesn't seem to help out! which include: https://www.npmjs.com/package/react-rails-form-helpers

https://www.npmjs.com/package/react-form

Is there any npm package for this? Using react_on_rails gem with Rails 5 stable

1

There are 1 answers

0
Aivils Štoss On

I ended up with manually written inputs, uncontrolled from reactjs view point.

<input type="text" name={`listing[working_time_slots_attributes][${value}][from]`}
            defaultValue={timeSlot.from} />

And axios, form-serialize npm.

import axios from 'axios';
import serialize from 'form-serialize';

handleSubmit(event) {
  event.preventDefault();
  const formData = serialize(event.target, { hash: true });

  // alert(`A data was submitted: ${JSON.stringify(formData, null, 2)}`);
  axios.post(`/api/listings/${this.props.listing.id}/update_working_time_slots`, formData)
  .then((response) => {
    this.setState({ timeSlots: response.data.working_time_slots }); // eslint-disable-line react/no-set-state
    console.log(response); // eslint-disable-line no-console
  })
  .catch((error) => {
    console.log(error); // eslint-disable-line no-console
  });
}