How do you make a React form start out with some values prefilled when editing?

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() {
  super();
  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.

Think your friends would dig this article, too?

Google+
Tumblr
Preview

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 React and see how to implement common form patterns.

The excerpt contains a table of contents and two chapters: on building an intuition for forms and handling various form controls.

No spam. I will occasionally send you my posts on JavaScript and React.
Preview

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 React and see how to implement common form patterns.

The excerpt contains a table of contents and two chapters: on building an intuition for forms and handling various form controls.