Hello everyone, recently I came across a new way to handle React forms, maybe its something you know, maybe you've been doing this for years and th...
For further actions, you may consider blocking this person and/or reporting abuse
Is better to use prevState argument when chaning state based of previous state because
setState
is asynchronous and may cause unstable updates.or in more short form:
Thank you for the suggestion.
In the second example you forgot to rename your handlers to
handleChange
. This could be confusing for newbies.Anyway it's a good start, but as some others told you, you should rely on form libraries. I tested a lot of them and I kind of like final-form for building big forms and reusable fields, then I would recommend you Yup for the validation. The latter is working pretty well with any form library by the way.
Formik + Yup is very good combo.
Yes I used Formik before but got issues with null values and complex forms. I didn't encountered any of those issues with final-form which I'm using in production for a year now
Thanks for pointing it out, I've updated it.
I totally agree that third party libraries are excellent way of handling React forms.
I just found about this way and thought it was pretty neat.
Nice – a couple things I had to tweak to get working, though:
<input />
elements need names likename="username"
, otherwise the change handler doesn't know which state value to updateconst handleChange(e){}
needs to either beconst handleChange = (e) => {}
orfunction handleChange(e){}
Thanks for pointing it out
I agree this is a good writeup!!
I'd also suggest adding a validation layer.
I know you want to keep this as a simple example but that is also something basic to always add when working on forms.
Between required fields to ensuring the dat isn't being submitted with empty strings.
Many things could be added in the validation layer
This is a solved problem already. React Hook Form, Formik, React Final Form, etc... are solid libraries.
This trick is very nice! Thanks for sharing.
You're welcome. Thanks for reading
Fun fact: *This is recommended of reactjs.org
Read more here: reactjs.org/docs/forms.html#handli...