Forms in React
Forms have always sucked a bit in React. Which is pretty frustrating given how much of web interactions are done with them.
Formik tried to solve this and did a pretty good job, until you wanted to do something a bit more complicated. For example I had a form where the user would select a value from a dropdown which triggers an API request to get the options for the next dropdown. If there was only a single option returned then I needed to set the value to that option. This proved far more complicated than I had hoped.
Hooks have also made the situation much easier to deal with, but if you're using lots of useState
calls to store individual fields then there can be quite a lot of boiler plate just to update a form field, and that's before you've considered doing other tasks such as validation.
function HookForm() {
const [ firstName, setFirstName ] = useState("")
const handleFirstNameOnChange = (e) => setFirstName(e.target.value)
const [ lastName, setLastName ] = useState("")
const handleLastNameOnChange = (e) => setLastName(e.target.value)
...
}
So what's the new way
I whipped up a (very) quick proof of concept over the weekend, and have called it FormUp (Reform was taken).
The idea is to declare the form using a fluent API in a similar way to how Yup validation schema's are written. The result from this hook will then give you everything that you need to not only render the form, but also to update any of the values and which fields have error messages etc.
const { fields, form } = FormUp.useFormUp({
name: FormUp.text(""),
email: FormUp.email(""),
dob: FormUp.date(""),
}, {
onSubmit: (e) => console.log("Submitted"),
});
...
return (
<FormUp.Form form={form}>
<FormUp.Input field={fields.name} />
<FormUp.Input field={fields.email} />
<FormUp.Input field={fields.dob} />
<button type="submit">Submit</button>
</FormUp.Form>
)
What's next
It's still very raw and certainly not ready for anyone to use. But I'm hoping to quickly add features to enable validation, value management. Let me know what you think. Is this likely to be useful or are we happy with Formik?
Top comments (2)
Hi Warren, I would suggest you to have a look into github.com/iusehooks/usetheform .
I like very much.