How can i use Nested forms in ReactJS?
Asked Answered
J

1

7

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

Judsonjudus answered 9/1, 2017 at 8:36 Comment(5)
@T.J.Crowder didnt get it?Judsonjudus
You can have a look at: guides.rubyonrails.org/form_helpers.htmlJudsonjudus
Ah, didn't know it was a term (mis)used by the helper: guides.rubyonrails.org/form_helpers.html#nested-formsTill
@HenrySamuel Did you find a solution to this?Gutty
Hi, any solutions?Enough
L
0

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
  });
}
Lissalissak answered 31/10, 2017 at 13:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.