Should a form for editing update the underlying model?

21 Mar 2017

In an imaginary world where forms are only ever used to enter something from scratch, what you know about forms in React might be enough. In the real world, however, forms are often lively creatures — you can come back to them and change your data.

Up until now, our forms were pretty stand-alone and isolated.

Forms for entering new data start out like this:

constructor() {
  this.state = {
    email: '',
    password: '',

and they are used something like this, perhaps:

<SignUpForm />

We can see they don’t receive any props, they keep the current values in the state, and they initialize the state with empty values. Which is perfect if all you need is to collect brand new data through the form.

But what if you had a different form… for editing a post, for example. It would somehow have to accept current title and body. Maybe like this:

<PostForm title={someTitle} body={someBody} />

Except now there are several possibilities as of how to go further with this:

Unlike with individual inputs, having a form “uncontrolled” is a preferred method to make a form. A form is not a way to change a thing directly, rather, it’s a request to change one.

Think about paperwork to change the name. It doesn’t directly change your name as you fill it in; it doesn’t “bind” to your name. It is just initialized with some data (your current name), and you fill in the new name and take it to bureaucrats before it has any effect.

And the same is often true of forms on the web — they do something only when submitted.

Get a free sample of The Missing Forms Handbook of React

You know how you tear your hair out when your designer asks to make a nice form?

But what if you could implement the form experience your users deserve?

The Missing Forms Handbook of React can help you breeze through your React forms. You will learn how forms fit into the React model. And, you are going to see how to implement common form patterns and structures.

No spam, promise. I hate it as much as you do!

, enjoying the article? Now think of 3 friends who are interested in React, Forms and would be into it, and share the link with them! 👇