Last active
April 30, 2018 09:59
-
-
Save JSila/09931fb917d6f8ef6d2faeb8bdb1a6bf to your computer and use it in GitHub Desktop.
withForm higher-order component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react" | |
const noop = () => false | |
const withForm = (fields, validateFn = noop, validSubmitFn) => WrappedComponent => { | |
class WithForm extends React.Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
form: fields, | |
errors: {} | |
} | |
this.onChange = this.onChange.bind(this) | |
this.onSubmit = this.onSubmit.bind(this) | |
} | |
onChange(e) { | |
this.setState({ | |
form: { | |
[e.target.name]: e.target.value | |
} | |
}) | |
} | |
onSubmit(e) { | |
e.preventDefault() | |
if (validateFn !== noop) { | |
const errors = validateFn(this.state.form) | |
this.setState({ | |
errors | |
}) | |
if (!errors) return | |
} | |
validSubmitFn({ | |
...this.props, | |
form: this.state.form | |
}) | |
} | |
render() { | |
return <WrappedComponent {...this.props} onChange={this.onChange} onSubmit={this.onSubmit} errors={this.state.errors} form={this.state.form} /> | |
} | |
} | |
WithForm.displayName = `WithForm(${WrappedComponent.displayName})` | |
return WithForm | |
} | |
export default withForm |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {withStateHandlers} from "recompose" | |
// initialState is {form, errors} object | |
const noop = () => {} | |
const withForm = (initialState, validateFn = noop, successFn = noop) => withStateHandlers( | |
initialState, | |
{ | |
onChange: () => e => ({ | |
form: { | |
[e.target.name]: e.target.value | |
} | |
}), | |
onSubmit: ({form, errors}, props) => e => { | |
e.preventDefault() | |
errors = validateFn(form) | |
if (Object.keys(errors).length) return {errors} | |
successFn(form, props) | |
return {errors} | |
} | |
} | |
) | |
export default withForm |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment