Rangle.io: React Training
gitbook
gitbook
  • Introduction
  • Setup
  • Functional JavaScript
  • ES6 constructs
    • Default Params
    • Template Literals
    • Destructuring
    • Arrow Functions
    • Promises
    • let and const
    • Modules
  • Thinking in Components
    • Atomic Design
    • Atomic Component Principles
    • Benefits of This Approach
    • The Process
    • Task #1
  • React Components
    • Stateless Components
    • Stateful Components
    • Stateful vs Stateless Components
    • Composition
    • Task #2
    • Task #3
    • Task #4
    • Task #5
  • Immutable
    • What Is Immutability?
    • The Case for Immutability
    • JavaScript Solutions
      • Object.assign
      • Object.freeze
    • Immutable.js Basics
      • Immutable.Map
        • Map.merge
      • Nested Objects
        • Deleting Keys
        • Maps are Iterable
      • Immutable.List
      • Performance
      • Persistent and Transient Data Structures
      • Official Documentation
    • Exercises
      • Task #1
      • Task #2
      • Task #3
      • Task #4
      • Task #5
      • Task #6
      • Task #7
  • Redux
    • Review of Reducers and Pure Functions
    • Redux Reducers
    • Redux Actions
    • Configuring your Application to use Redux
    • Using Redux with Components
    • Redux and Component Architecture
  • Routing
    • React Router
    • Router Redux
  • Forms
    • Redux Form
  • Testing
    • Setup
    • Components
    • Reducers
    • Actions
Powered by GitBook
On this page
  • Setup
  • Reducer
  • Wrapper
  • Form
  • Validation
  • Full Example

Was this helpful?

  1. Forms

Redux Form

PreviousFormsNextTesting

Last updated 6 years ago

Was this helpful?

Setup

npm install redux-form

Reducer

Redux-form provides a reducer that manages the form's state. Add this to the combineReducers. It is important to specify the state reducer key as form for redux-form to work

import {reducer as formReducer} from 'redux-form'

const reducer = combineReducers(Object.assign({}, reducers, {
  ...
  routing: routeReducer,
  form: formReducer,
}))

Wrapper

Redux-form provides a redux-form wrapper to pass your component props as callbacks (resetForm, handleSubmit) and form data (error, dirty, fields, submitting). View the .

export default reduxForm({
  form: 'formKey',          // form key must be unique
  fields: ['name', 'email'] // form fields
  ...
  validate                  // custom form validation function
})(Form)

Form

The fields props contains the field values (i.e. name, email) and several event listeners for each field, so these must be passed into the input tag for the specific field via {...name}.

import React, {Component} from 'react';
import {reduxForm} from 'redux-form';

const submit = (formValues, dispatch) => {
    ...
}

class Form extends Component {
  render() {
    const {fields: {name, email}, handleSubmit} = this.props;
    return (
      <form onSubmit={handleSubmit(submit)}>
          <label>First Name</label>
          <input type="text" placeholder="Name" {...name}/>
          <label>Last Name</label>
          <input type="text" placeholder="Email" {...email}/>
          <button type="submit">Submit</button>
      </form>
    )
  }
}

For submission of form data, the handleSubmit prop is passed to the onSubmit or onClick and will complete any validations before calling this.props.onSubmit(data). You can also pass a function into handleSubmit to be called, so handleSubmit(submit).

Validation

The validate function will be called on each render cycle and will be passed the a form values object where the function must return an errors object with the specific error message for each field.

const validate = fields => {
  const errors = {}
  if (!fields.name) {
    errors.name = 'Required'
  }
  if (!fields.email) {
    errors.email = 'Required'
  } else if (!/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i.test(fields.email)) {
    errors.email = 'Invalid email address'
  }
  return errors
}

The keys for the input field values and output errors objects must match the form fields specified (i.e. name, and email).

Full Example

import React, {Component} from 'react';

const validate = values => {
  const errors = {};
  if (!values.name) {
    errors.name = 'Required';
  }
  if (!values.email) {
    errors.email = 'Required';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email';
  }
  return errors;
}

class Form extends Component {
  render() {
    const {fields: {name, email}, handleSubmit} = this.props;
    return (
      <form onSubmit={handleSubmit(submit)}>
          <label>First Name</label>
          <input type="text" placeholder="Name" {...name}/>
          <label>Last Name</label>
          <input type="text" placeholder="Email" {...email}/>
          <button type="submit">Submit</button>
      </form>
    )
  }
}

export default reduxForm({
  form: 'formKey',          // form key must be unique
  fields: ['name', 'email'] // form fields
  ...
  validate                  // custom form validation function
})(Form)

Check out for more form examples.

full list of props
Redux Form