Using the native form element with React

Gilad lev-ari
2 min readJan 9, 2022

I’m gonna something that some of you might like but most of you might not. You should use the native HTML form element. What I actually mean is that you should use it without using any form mange library, such as formik, react-hook-form, redux-form or any other forms library. They are all great libraries and in 99% of the time they will just do the job (so you may stop reading if you like). BUT! They also require you to read the documentation and there is this 1% where they are just not good enough. Why should you choose one over the other? What is going down under the hood in each library?

That is why I think using the native HTML form element is a better choice.
Here is the part where you say, “But writing form in React is hard!!!”. I guess the correct thing to say is “writing forms in HTML is ugly”.
In my opinion, those libraries, wont make it any less ugly (or any prettier).

So what do I suggest? You should use the native HTML form element (obviously) 😄. How? by creating your own simplest hook and validation function.

We will start by creating the validation function

The main star of the above code, is the validateForm function. which gets the form data and an array of validations to check.
We will use it on our useForm hook.

It is a simple hook which gets the validations to check when the form is submitted and the submit call back function once all validations are ok.
off course we can add useMemo for performance, but I wanted to make it simple.

And now for the main show!!! 🥁🥁🥁

Using our useForm hook by passing it an array of validations and the submit call back function, we can use the HMTL form element any way we like. This will work with or without a UI library such MUI or ANT or what ever it is just native HTML.
And … If you have a very large form, you can even split it into sub components and do something like this:

<form onSubmit={onSubmit}>
<MyPartialFormNumber1 />
<MyPartialFormNumber2 />
<MyPartialFormNumber123 />

And it will work like it was one long file.

One last note: My validation function, is a simple function, it only returns true if the field is invalid ({name:true,email:true...}) but you can make it more sophisticated, by checking the exact error and return a message instead or you could even use a validation library instead.

Here is the full example.

That’s it. I hope you liked this post and found it useful.



Gilad lev-ari

Full stack web engineer with over a decate of experience and true passion for front end development and JavaScript 💪