In VanilaJs we take data from form during onSubmit, using FormData make request. In ReactJ documentation we see that before submit it's remended 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?
In VanilaJs we take data from form during onSubmit, using FormData make request. In ReactJ documentation we see that before submit it's remended 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?
Share Improve this question asked Jan 16, 2019 at 9:57 IgaIga 3331 gold badge4 silver badges18 bronze badges 2- 2 In short, yes. Collect the data typically onChange into the ponent state, then onSubmit preventDefault() + send the data as a POST to your api. – nanobar Commented Jan 16, 2019 at 10:01
- reactjs/docs/forms.html#fully-fledged-solutions – SLCH000 Commented Jan 16, 2019 at 12:10
3 Answers
Reset to default 3You 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 ponent 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 bee plicated 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.