Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  7] [ 6]  / answers: 1 / hits: 30388  / 7 Years ago, sat, january 20, 2018, 12:00:00

I'm actually new to React, and can't choose, what is the best way to store data in a situation like this:
I have a form with some inputs, and I need to do some actions with all data from these inputs on submit.
All inputs are stored in one Component.
So, I need to get all the data only on submit. And now I'm trying to choose the best way to store this data. I see 2 ways:




  • Storing data in the state. But as React Docs describes:




    Only data which need to render may store in the state.




    But I don't need this data for render, I need to work with this only on submit.


  • Storing as class variables. It looks good for me, because when i
    using state, i need to call setState(), which trigger render(which i
    don't need), or this.state.data = ....But React Docs says that:




    You may change state directly only in constructor.





So, which of these ways are better and why?


More From » reactjs

 Answers
25

I think you're overthinking it, just stick with controlled components and manage your form data through state.



However, if you really don't want to use controlled components because you don't want the render method to be called then you don't have to.



This is because form elements work a little bit differently from other DOM elements in React, because in HTML, form elements such as <input>, <textarea>, and <select> naturally maintain their own state and update it based on user input. See official forms docs.



And React doesn't take that away from you. This means that you can make use of forms the same way you would with vanilla JS.



Also worth mentioning that in React world this way of leaving data to be purely handled by the DOM rather than handling it with a React Component is known as Uncontrolled Component.



Implementation



As far as how this would look in practise, I can think of two ways that you can do this, one would be with refs:



handleSubmit = (e) => {
e.preventDefault();
console.log(this.input.value); // whatever you typed into the input
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<input type=text name=name ref={input => this.input = input} />
<input type=submit value=submit />
</form>
);
}


Another way would be through an event object:



handleSubmit = (e) => {
e.preventDefault();
console.log(e.target.name.value); // whatever you typed into the input
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<input type=text name=name />
<input type=submit value=submit />
</form>
);
}

[#55414] Tuesday, January 16, 2018, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlynd

Total Points: 470
Total Questions: 108
Total Answers: 120

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
;