/
posts_new.js
79 lines (70 loc) · 2.03 KB
/
posts_new.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import React, { Component } from "react";
import { Field, reduxForm } from "redux-form";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import { createPost } from "../actions";
class PostsNew extends Component {
renderField(field) {
const { meta: { touched, error } } = field;
const className = `form-group ${touched && error ? "has-danger" : ""}`;
return (
<div className={className}>
<label>{field.label}</label>
<input className="form-control" type="text" {...field.input} />
<div className="text-help">
{touched ? error : ""}
</div>
</div>
);
}
onSubmit(values) {
this.props.createPost(values, () => {
this.props.history.push("/");
});
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
<Field
label="Title For Post"
name="title"
component={this.renderField}
/>
<Field
label="Categories"
name="categories"
component={this.renderField}
/>
<Field
label="Post Content"
name="content"
component={this.renderField}
/>
<button type="submit" className="btn btn-primary">Submit</button>
<Link to="/" className="btn btn-danger">Cancel</Link>
</form>
);
}
}
function validate(values) {
// console.log(values) -> { title: 'asdf', categories: 'asdf', content: 'asdf' }
const errors = {};
// Validate the inputs from 'values'
if (!values.title) {
errors.title = "Enter a title";
}
if (!values.categories) {
errors.categories = "Enter some categories";
}
if (!values.content) {
errors.content = "Enter some content please";
}
// If errors is empty, the form is fine to submit
// If errors has *any* properties, redux form assumes form is invalid
return errors;
}
export default reduxForm({
validate,
form: "PostsNewForm"
})(connect(null, { createPost })(PostsNew));