user2490003
user2490003

Reputation: 11890

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!

Upvotes: 8

Views: 23583

Answers (2)

Pedram
Pedram

Reputation: 16575

For those who want to use Serialize form in ReactJs with functional component try this:

1. Create a state

const [form, setForm] = useState({});

2. Create a function handler

const handleForm = (name, value) => {
     setForm({...form, [name]: value});
}

Now you got your object here:

const handleSubmit = () => {
     console.log(form);
}

3. In your render

<form>
     <input onChange={(e)=>handleForm('name', e.target.value)} />
     <input onChange={(e)=>handleForm('phone', e.target.value)} />
     <button onClick={()=>handleSubmit()}>Submit</button>
</form>

UPDATE 2022

Or use useForm

useForm is a custom hook for managing forms with ease. It takes one object as optional argument. The following example demonstrates all of its properties along with their default values.

Upvotes: 0

Cjmarkham
Cjmarkham

Reputation: 9681

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

Upvotes: 9

Related Questions