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

17,108

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

Share:
17,108

Related videos on Youtube

user2490003
Author by

user2490003

Updated on September 16, 2022

Comments

  • user2490003
    user2490003 over 1 year

    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!