React Form: Prefill Form Fields With Saved Data

We've learned a lot about validation in the previous posts. Let's do something different today. Most often when user submits data through a form in our application, they can pull it out again for editing. Like in social media or market places where they change their profile or product information.

So how do we make our form get prefilled values?

Considering form values are set from state, we obviously have to do something with our constructor method so that it will accept data sent to its component.

this.state = {
      email:  '',
      username: '',
      password: '',
}

The easiest way to do that is to pass props from our parent component into our form component. For this tutorial, let's simulate how we will present email, username and comment data for updating. We have to create a dummy user and pass it into our form component.

const user = {
  email: "johndoe@mail.com",
  username: "JohnDoe",
  comment: "Everyones favorite colleague at work",}

ReactDOM.render(<App data={user}/>, document.getElementById('root'))

With the data available to our component, now we have to initialize the form state via props. We will assign data OR empty to our state in accordance with the props being passed or not.

this.state = {
      email:  props.data.email || '',
      username: props.data.username || '',
      comment: props.data.comment || '',
}

Also, make sure the constructor call have props parameter, or it will trigger an error

constructor(props)

One last thing

Since our form stored the validity of fields in the state, we also have to change how the validity value is being initialized. Set email and username validity to true if there are props data coming.

formValidity: {
        email: props.data.email? true : false,
        username: props.data.username? true : false, 
        password: false, 
        passwordConfirmation: false,
      }

This way we just have to fill in the password for submitting our data. Check out the code here.

Want To Learn More?

I have been developing React form extensively for a business application that required all the features I have written during the past few weeks. It turns out building forms with React is both hard and challenging. I'm currently writing a comprehensive guide to forms in React from beginner to advanced. Unlike my tutorials, the book will include a real form practice and source code which will be interesting if you are building a form with React.

As always, thanks for reading 🌼


Get my weekly newsletter ✉️
Let's explore the exciting world of React together.
No Spam. Unsubscribe anytime