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);
Last active
March 1, 2017 17:28
-
-
Save alanbsmith/68cd348dc07c714c4a5d26a45c954442 to your computer and use it in GitHub Desktop.
Redux Uncontrolled Form Pattern
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
added a
ref
tag. Going to see if this actually works now.