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() {
  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?

If you need a mobile app built for your business or your idea, there's a chance I could help you with that.
Leave your email here and I will get back to you shortly.