How to better handle form state data with ReactJs
There are several ways, such as libs, to handle form data with ReactJS. The purpose of this article is to show that the following instructions make your React Component more dynamic, less hard code and easier to manage.
Let’s go! Take a look at this code:
The logic above was to create a state for each field, then using the Switch, it is being checked which value of the name attribute and then set it in the corresponding state.
How about that?
Uhuul 🙌 !
Did you get the idea? Let’s see…
It was necessary to create only 1 default state for object {}
, you can even set the keys and default values, but it is not necessary in that example (see below why)… Moving on, over there, in the handleChange()
function I call the state and I look for the key using bracket notation by giving e.target.name
as the key and the value coming from e.target.value
. In that case, when javascript does not find the key it adds the key and the value, if it does, javascript updates only the value.
Oops I know, we work with immutability, let’s get there. Now that I have the state, this moment (important to understand this), receiving the key and the value, just update the entire state, it will be enough.
So, it comes with setMessageForm({...messageForm})
on line 10. It gets involved to update the state of the messageForm
using a copy of the previous state. Then you will ask… “Sorry but, in the next interaction, it will come back to the previous state?”, No! Remember the explanation above? If the next e.target.name is the same it will update, if different it will add!
So, then, we have now a more dynamic form, it is not necessary, in that example, to add any new key, or to apply a new rule in our handleChange()
function, we just add the necessary inputs
. :)
That’s is the trick!
A little hard to understand? Test there:
Did you like the article? I hope so! Click on how many claps (from 1 to 50) you think the article you deserve, share it with the community and leave your comment!
Do you want more? Let’s connect on Linkedin.