What is the best practices to work with forms in ReactJS?

Viewed 5752

In VanilaJs we take data from form during onSubmit, using FormData make request. In ReactJ documentation we see that before submit it's recommended to setState data which introduced user.After onClick on submit button we take this data from the state and make request. So is it best way to work with forms using React?

3 Answers

You can do the same as your old approach here as well, but the problem is that your are delaying form submission since HTML Collections take more time to iterate than looking up and managing states. Look at the example:

import React from 'react';

class Login extends React.Component {
  login(event) {
    event.preventDefault();

    const data = {};
    const inputs = event.getElementsByTagName('input');

    for (let input of inputs) data[input.id] = input.value;

    // send `data` to server to test for login

    console.log(data);
  }

  render() {
    return (
      <form onSubmit={this.login}>
        <input id="email" type="email" />
        <input id="password" type="password" />
        <button type="submit">Login</button>
      </form>
    );
  }
}

Just imagine the time taken to fetch from the DOM and then iterating each element, versus managing state on each keypress during form submission.

Depending on the size of your project, there have been a lots of packages that handle form submission easy, e.g: formik, redux-form, react-final-form, to name few. But most of these use the same technic. For example formik does right just that and also handles some edge cases for you so that you don't have to worry about.

Briefly, I would say yes, that's the best way or at least the react way, to handle form data.

They are multiple way of doing form in react, and many doesn't involve the state.

Many people use redux for storing their application states.

You can, of course, use your component state, but you can also use redux-form (popular) or formik (lightweight).

Storing into the state is as easy as storing into an object, but then it can become complicated to store everything in one place in your React DOM..

This is why redux exist and why you should read what it is, it will help your to get the answer.

Related