Last active
July 9, 2018 12:57
-
-
Save quinn/b383070691bb9a32b675152aabdada41 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 FormContext = React.createContext({ | |
formState: {}, | |
update: () => {}, | |
}) | |
export class Form extends React.PureComponent { | |
state = { | |
formState: {}, | |
update: (name, value) => | |
this.setState(state => ({ | |
formState: { | |
...state.formState, | |
[name]: value, | |
} | |
})) | |
} | |
onSubmit = () => | |
this.props.onSubmit(this.state.formState) | |
render () { | |
return <FormContext.Provider value={this.state}> | |
<form onSubmit={this.onSubmit}> | |
{this.props.children} | |
</form> | |
</FormContext.Provider> | |
} | |
} | |
export const Input = ({ name }) => | |
<FormContext.Consumer> | |
{({ formState, update }) => | |
<input onChange={({ target }) => update(name, target.value)} value={formState[name]} /> | |
} | |
</FormContext.Consumer> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment