Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize <form> data in React JS to submit POST request

I have a very basic comment form that takes some text input from a user and sends a POST request via AJAX to create a new comment.

var CommentForm = React.createClass({
  propTypes: {
    // ...
    // ...
  },

  handleFormSubmit: function(e) {
    e.preventDefault();

    var component = this;

    return $.ajax({
      type: "POST",
      url: this.props.someURL,
      data: // ???? - Need to figure out how to serialize data here,
      dataType: "json",
      contentType: "application/json",
      success: (function(response){ alert("SUCESS") }),
      error: (function(){ alert("ERROR"); })
    });
  },

  render: function() {
    var component = this;

    return (
      <form onSubmit={component.handleFormSubmit} className="comments__form" id="new_comment" accept-charset="UTF-8">
        // ...
      </form>
    );
  }
});

I need to serialize the form data to send along with my POST request, but I'm not sure how. I know in JQuery I can select the form element and do something like $("#my_form").serialize(), but I can't seem to call that from inside the React component (not sure why?)

Some other stackoverflow answers suggested adding a ref='foo' to each relevant DOM element and then I can access them with React.findDOMNode(this.refs.foo).getValue();. This works fine but it leaves me to manually construct the whole serialized form data string, which isn't pretty if the form is a lot longer and complex.

// Sample serialized form string
"utf8=✓&authenticity_token=+Bm8bJT+UBX6Hyr+f0Cqec65CR7qj6UEhHrl1gj0lJfhc85nuu+j2YhJC8f4PM1UAJbhzC0TtQTuceXpn5lSOg==&comment[body]=new+comment!"

Is there a more idiomatic way to approach this - perhaps a helper that will let me serialize my form data within ReactJS?

Thanks!

like image 804
user2490003 Avatar asked Aug 13 '16 23:08

user2490003


People also ask

How do you serialize data in a form?

To serialize a FormData object into a query string, pass it into the new URLSearchParams() constructor. This will create a URLSearchParams object of encoded query string values. Then, call the URLSearchParams. toString() method on it to convert it into a query string.

How do I pass form data to API in React?

Before passing the form data name, email and mobile number, we need to stringify it. JSON. stringify() function will take care of it. let res = await fetch("https://httpbin.org/post", { method: "POST", body: JSON.

How do you serialize data in JavaScript?

In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() . CSS values are serialized by calling the function CSSStyleDeclaration. getPropertyValue() .


1 Answers

You would usually use the component state to store all the information.

For example, when an inputs text is changed, you would change the state to reflect that:

<input type="text" onChange={ (e) => this.setState({ text: e.target.value }) }

Then, when it comes to submit the form you can access the value using this.state.text.

This does mean that you would have to build the object yourself however, although, this could be achieved via a loop:

this.state.map((value, index) => {
  obj[index] = value;
});

and then send obj as the post data.

UPDATE

The only performance issue with updating the state is that the component is re-rendered each time. This isn't an issue and is the way react components work, as long as you watch for the size of the render method and what it is doing.

Forms in the usual HTML <form> tag sense, don't exist within React. You use the form components to change the state. I suggest reading up on React Forms

In terms of the UTF8 flag, that would be the value of a hidden field, so you could use refs in this case to get that value for your object:

<input type="text" ref="utf8" value="✓" />

obj.utf8 = this.refs['utf8'].value

like image 191
Cjmarkham Avatar answered Oct 23 '22 11:10

Cjmarkham