Last active
February 7, 2020 16:59
-
-
Save mattboldt/9e24d44f1b569ba970c6971ebab08152 to your computer and use it in GitHub Desktop.
React Form refactor
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
// 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> | |
} |
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
// 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: '[email protected]' } | |
// 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