Skip to content

Instantly share code, notes, and snippets.

@alanbsmith
Last active March 1, 2017 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alanbsmith/68cd348dc07c714c4a5d26a45c954442 to your computer and use it in GitHub Desktop.
Save alanbsmith/68cd348dc07c714c4a5d26a45c954442 to your computer and use it in GitHub Desktop.
Redux Uncontrolled Form Pattern
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';

class Form extends Component {
  constructor(props) {
    super(props);
    
    this.state = {
      errors: {
        projectName: false,
      }
    };
  }
  
  handleSubmit(e) {
    e.preventDefault();
    const { projectName } = this.refs;
    
    if (this.formIsValid()) {
      this.props.dispatch(submitForm(projectName));
    }
  }

  formIsValid() {
    const { errors } = this.state;
    // this can be done in Lodash without a for loop
    // but to eliminate external libs
    for(let key in errrors) {
      if (errors[key]) { return false; }
    }
    return true;
  }

  validateField(e) {
    const { name, value } = e.target;
    const errors = {};
    switch (name) {
      case 'projectName':
        errors[name] = !!value.length;
        break;
      default
        return errors[name] = false;
    }
  }

  render() {
    const { erorrs } = this.state;
    return (
     <form
       onSubmit={e => this.handleSubmit(e)}
     >
       <input
         defaultValue={this.props.projectName}
         className={`form-input ${errors.name ? 'error' : ''}`}
         onChange={e => this.validateField(e)}
         ref="projectName"
         type="text"
       />
       <button
         type="submit"
       >
         Submit
       </button>
     </form>
    );
  }
}

function mapStateToProps(state) {
  return {
    projectName: state.project.name,
  };
}

export default connect(mapStateToProps)(Form);
@alanbsmith
Copy link
Author

added a ref tag. Going to see if this actually works now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment