Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save busypeoples/6f2ead1dac8e47eb61b459eb8b24026f to your computer and use it in GitHub Desktop.
Save busypeoples/6f2ead1dac8e47eb61b459eb8b24026f to your computer and use it in GitHub Desktop.
import React from 'react'
const enhancedForm = Component =>
class HigherOrderComponent extends React.Component {
constructor(props) {
super(props)
this.state = { form: props.initialState }
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
}
handleSubmit(e) {
e.preventDefault()
console.log(JSON.stringify(this.state, null, 4))
}
handleChange(e) {
const target = e.target
const name = target.name
const value = target.type === 'checkbox'
? target.checked
: target.value
this.setState(state => ({form: {...state.form, ...{[name] : value}}}))
}
render() {
const { initialState, ...rest } = this.props
const { form } = this.state
return React.createElement(Component, {
state: form,
handleSubmit: this.handleSubmit,
handleChange: this.handleChange
})
}
}
const Form = ({state, handleSubmit, handleChange}) =>
(<form onSubmit={handleSubmit}>
<label>
First Name:
<input
type="text"
name="firstName"
value={state.firstName}
onChange={handleChange}
/>
</label>
<br />
<label>
Last Name:
<input
type="text"
name="lastName"
value={state.lastName}
onChange={handleChange}
/>
</label>
<br />
<label>
User Name:
<input
type="text"
name="userName"
value={state.userName}
onChange={handleChange}
/>
</label>
<br />
<label>
Confirm User Name:
<input
type="text"
name="confirmUserName"
value={state.confirmUserName}
onChange={handleChange}
/>
</label>
<br />
<label>
Notifications:
<input
name="notifications"
type="checkbox"
checked={state.notifications}
onChange={handleChange} />
</label>
<br />
<button>Submit</button>
</form>)
export default enhancedForm(Form)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment