Skip to content

Instantly share code, notes, and snippets.

@JSila
Last active Apr 30, 2018
Embed
What would you like to do?
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