Skip to content

Instantly share code, notes, and snippets.

@mattboldt
Last active February 7, 2020 16:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattboldt/9e24d44f1b569ba970c6971ebab08152 to your computer and use it in GitHub Desktop.
Save mattboldt/9e24d44f1b569ba970c6971ebab08152 to your computer and use it in GitHub Desktop.
React Form refactor
// Consider this as option A: binding to input fields and listening to their changes:
// in a react component
submit = (e) => {
MyAjaxApi.post('url.com', {
user_name: this.state.name
})
}
handleNameChange = (e) => {
this.setState({ name: e.target.value })
}
handleEmailChange = (e) => {
this.setState({ email: e.target.value })
}
render() {
return <div>
<!-- these are *controlled* inputs! -->
<input onChange={this.handleNameChange} value={this.state.name} />
<input onChange={this.handleEmailChange} value={this.state.email} />
<button onClick={this.submit}>submit</button>
</div>
}
// And option B: leveraging `FormData`
handleSubmit = (e) => {
e.preventDefault()
// Use our this.form ref we set in `<form>` below
const form = this.form
// Use the `FormData` API
const data = new FormData(form)
// Translate our `FormData` object to api-friendly json
const jsonFormData = Object.fromEntries(data)
//=> Output: { user_name: 'Matt', user_email: 'me@matt.com' }
// Use whatever ajax method to post
MyAjaxApi.post('url.com', jsonFormData)
}
render() {
return <form onSubmit={this.handleSubmit} ref={(el) => (this.form = el)}>
<!-- these are *uncontrolled* inputs! -->
<input name="user_name" defaultValue={this.state.name} />
<input name="user_email" defaultValue={this.state.email} />
<button>submit</button>
</form>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment