user2490003 user2490003 - 2 months ago 76x
React JSX Question

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

request via AJAX to create a new comment.

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

handleFormSubmit: function(e) {

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">
// ...

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

Some other stackoverflow answers suggested adding a
to each relevant DOM element and then I can access them with
. 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

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



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: }) }

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:, index) => {
  obj[index] = key;

and then send obj as the post data.


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