Newer Post

Slack Tips Tuesday: How to not look like a slacker on Slack

Older Post

Slack Tips Tuesday: How a Developer's Daily Update Should Look

Forms in React and Redux

In this tutorial we are going to implement a simple React library for creating, composing and serializing form elements.

The goal is to allow developers to create forms with minimal code amount and maximal flexibility of the composition. The library should have the built-in validation and return serialized data on submit. Using the library shouldn’t require any extra code but simple declaration of an order, types, names and validation rules. The whole internal data flow will be hidden in the implementation.

Let’s get started.

Our tech stack

One thing I love in React the most is its simplicity. It allows me to write my views as reusable components being functions of the state – I give them the model and they render the view, nothing more. React takes full responsibility for re-rendering, managing the view transitions and this is done in a very efficient way.

What React cannot do for me though is state and data managing. Remember – it’s only a view library, we have to organise the data flow around the views separately.

Fortunately, React works perfectly with well-known patterns commonly used for a long time. We’re using redux as a way to manage data flow.

To use redux, we have to implement two elements: action creator and state reducer. These names might sound scary, but the idea is really simple.

To fully understand how redux works and how powerful it can be, I recommend watching the presentation and lessons on egghead by Dan Abramov, the author of redux.

To simplify the whole process, we will use ready components from the Material UI to avoid extra styling and focus on composing and validation of the form.

Bootstrapping the project

First let’s set up the project and the environment. I assume you have node already installed. Create a new folder and initialize the new npm project using npm init.

You can either follow along in this article, or view the final result here

We need a tool for building your scripts into the one minified file – webpack is IMO an excellent choice for this purpose. Code will be written in ES2015 (aka ES6) and JSX syntax, so you also need the babel plugin to convert the code into a version readable for all modern browsers.

Begin by installing webpack globally: npm i -g webpack. Then install plugins and all required dependencies locally: npm i --save-dev webpack@^1.0.0 babel-loader babel-preset-es2015 babel-preset-react path.

Create a new file called build.config.js, containing the following configuration script:

Add build aliases at the end of package.json:

Install react modules: npm i -S react react-dom. Create a file called demo.js – we will import modules from the library there and render the example form to see the results. For now it renders an empty div:

To run the demo, we have to open an html file. Create a folder called dist and put file demo.html with simple markup loading the script:

Now you can run build process with the watcher to see if it works: npm run watch

Webpack will compile the demo and start watching for changes in the code. You should see output similar to the one below:

Congratulations! The environment is ready for coding.

Form component

Create the first component called Form. It’s going to be the root component for fields nested inside:

The code above doesn’t add any extra value when we compare it with using the simple <form>...</form>. Our component should store the data from its children. To achieve this, we have to connect this component to redux.

Start with creating constants for action types. We will use them to define and recognize actions in action creators and the store:

Action creator is a function returning callback for dispatching an action. Within an action we can for example make an AJAX call and then dispatch one or many actions. Redux injects callable action to the component as a prop. When we want to trigger an action in the component, we simply call the action with required data passed as an argument.

Create two action creators for updating and resetting the form data:

These actions will be passed into the Form component.

Now we can respond to the actions and modify data in the model using reducers. Reducer is another function, which takes the current state and returns the new one based on the action. Redux puts the new state to the components and View is being re-rendered.

Install lodash.assign (npm i -S lodash.assign) and create the store:

In redux, our model is a reducer – simple function which reduces the current (or initial) state to the new one based on the action data (so it works in the same way as function passed to Array.prototype.reduce)

Important! If we modify the state, the reference of the state must also change (redux propagates changes by checking references), so always create the new objects – that’s why I used assign({}, ...) in the return statements above.

Now connect action creators, store and the root component together.

Install extra modules required to use redux with our component: npm install --S redux react-redux redux-thunk redux-logger react-tap-event-plugin@^0.2.0

Create a wrapper for the Form:

A few lines, but also lots of the new code:

  • connect()  takes the React component, a function returning the current state and actions. It returns the smart component with all three elements bound together.
  • <Provider> is responsible for connecting all its smart children with the actual store.
  • reduxMiddleware is a simple middleware between dispatching actions and calling reducers. In this case we compose two middleware elements: redux-thunk, and redux-logger: - redux-thunk is used for dispatching asynchronous actions (read more),
  • redux-logger is used for logging all dispatched actions in the console so we can easily track them.
  • injectTapEventPlugin is a fix required by material-ui

Text field

Create the first visible element – a text field. Install material-ui and create the component:

The code above wraps TextField and passes the props. We have to export this component to allow the programmer for importing it – add the following line at the end of index.js:

Let’s try to render the first example to see how the rendering code will look like:

There is a problem: how to update the model in Form when user types some text? In the above example we actually defined all we need – the model is stored in Form, name of the field is defined too, our library has all required information.

Let’s not spoil this simplicity: we can hide the passing of data between components inside the implementation of our library. We have to use React’s feature called context.

Using React context

Occasionally, you want to pass data through the component tree without having to pass the props down manually at every level. React’s “context” feature lets you do this.

Add the following code to src/components/Form.js:

Form now exports the model and actions via the context so they can be used in its child components.

Update Text to see how it works:

- value is removed from the props, we get it from the context now: this.context.values[]
- model is updated on input change via the action in context: this.context.update(, value)

Let’s see how it looks. Run npm run build if you haven’t already, and open dist/demo.html in a browser:

Screenshot 2016-01-29 18.36.23


Now if we are able to compose text fields in the form, it’s time to implement some validation. Let’s start with implementing three example rules (install valid-url and email-validator before):

Each validator is a function returning an array with errors. If the returned array is empty – validation has passed.

But how to apply these validators to the Text field? Take a look:

- validate has been added to the props, so programmer can define an array with rule names that should be applied.
- isValid is called on blur. It iterates through the rules, call each of them and returns array with the errors - text with errors is passed to the TextField - updateValue has changed slightly. When user gets back to the field with errors, we refresh validation on each change. If the value is correct, errors should disappear immediately.

Update the demo:

Refresh the demo and see how it works:

Screenshot 2016-01-29 18.39.08

Before we submit the form, we need to check the validation status in all nested elements and prevent submission if one of the field is filled incorrectly.

The idea is to register isValid method in Form component from the field component, using the context (install lodash.without before):

- registerValidation adds a reference of the validating function to the array (used when field component is mounted) and returns another function removing the same reference from the register
- isFormValid checks registered validation functions and returns true or false. This method is also injected into the context, so all nested components can check if the form is valid or not - submit checks if the form is valid, sends copy of the model to the callback function and resets the model to the initial state (see reset action creator)

Update Text component as well:

Validation method is registered on mounting, removeValidationFromContext is stored and called on unmounting.


Once we can check form validation locally and globally, let’s implement the submit button:

- isFormValid is taken from the context
- If isFormValid returns false, the button is disabled - When button is clicked, we call submit action from the context

Export the new component same as others:

Update the demo:

and see how it works:

Screenshot 2016-01-29 18.41.41


Congratulations! We have learned a few nice things together:

  • how to set up new ES2015 project using webpack and babel
  • how to use redux
  • how to use React’s context
  • how to take advantage of JSX design to create simple composition concept
  • how to hide implementation details away in the library

The final code is available on GitHub.

Now, if you get the idea, you can freely scale your new library to handle all types of fields: passwords, check boxes, radio groups, datepickers, selects and literally any custom inputs you can imagine.

Also, these ideas are worth considering:

  • try refactoring validators and custom fields into separate npm modules and compose them as needed rather than grouping everything in the one library
  • create additional layer of abstraction to make switching from material-ui to other components possible (eg. if you want to apply your own styles)
  • initialize new fields with default value using context to avoid missing properties in the model

If you have any questions, catch me on Twitter (@KasperWargula).

Extra resources

We'll help you unleash.

Join the 20,000 developers who subscribe to our newsletter.

Scale your
Development team

We help you execute projects by providing trusted developers who can join your team and immediately start delivering high-quality code.

Hire Developers