Created
June 28, 2017 17:02
-
-
Save busypeoples/6f2ead1dac8e47eb61b459eb8b24026f to your computer and use it in GitHub Desktop.
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 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