Skip to content

Instantly share code, notes, and snippets.

@quinn
Last active July 9, 2018 12:57
Show Gist options
  • Save quinn/b383070691bb9a32b675152aabdada41 to your computer and use it in GitHub Desktop.
Save quinn/b383070691bb9a32b675152aabdada41 to your computer and use it in GitHub Desktop.
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