George Borunov

The experienced Software DeveloperConsultantProject managerEntrepreneur

Building forms with React and Redux

Today I’m going to share my experience with writing React components that collect user input, handle image uploading, and communicate with API to load or persist data.

For the purpose of persisting the state of input fields you could write your own components, but there’s absolutely no reason to do so, as there are several npm packages exist that do it all for you, and have a decent documentation & support available. I’ll list just a few options:  redux-forms, react-redux-formformsy-react.

My package of choice is react-redux-form. Its documentation turned out to be easily understood, and package itself has all features you may need to use with your forms. Though redux-forms has more stars on github and it seems to be a good choice as well, I wish it had a better documentation, and code samples for main use cases.

Alright, so let’s start off by creating a form reducer for Redux store:

Here we use  combineForms() function that allows us to have multiple forms. If you don’t need more than one form, however, you may consider using  formReducer() instead.

Then we’re getting back to our component and create a form:

Here we’ve created a simple form with name, gender, and avatar fields. It also validates required inputs and shows validation messages below.

The component accepts two props: myForm  which is an object that holds our form’s state (I’ll explain what that means below), and submit  – a function that handles form submission.

Next, we’ll create a container that will pass required props to the component:

Here, myForm  refers to the state of our form, which includes all low level details such as validity of each field, general state of the form (pending/submitted), and so on. Check out myForm  object to see all contained data.

The last step is creating an action that makes API call, sets validation errors from the backend, if there’s any, or marks form as submitted otherwise.

formActions.submitFields dispatches an action which will update the form status, and set validity. Note, that in order to have validation messages set correctly, in case of failure, the response from /api/v1/user should be in the following format:

Where each key in the object corresponds with a key from the form model.

Now we know how to build simple, yet customizable forms that validate user input, store fields data in redux store, can transmit data to a backend, and handle backend responses to display additional error messages.


Leave a comment

Your email address will not be published. Required fields are marked *