Skip to content

Instantly share code, notes, and snippets.

@JSila
Last active April 30, 2018 09:59
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 JSila/09931fb917d6f8ef6d2faeb8bdb1a6bf to your computer and use it in GitHub Desktop.
Save JSila/09931fb917d6f8ef6d2faeb8bdb1a6bf to your computer and use it in GitHub Desktop.
withForm higher-order component
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
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