Created
October 3, 2018 17:14
-
-
Save whoisryosuke/578be458b5fdb4e71b75b205608f3733 to your computer and use it in GitHub Desktop.
React - Handling forms and submitting POST data to API -- @see: https://reactjs.org/docs/forms.html
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
class NameForm extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { name: '' }; | |
} | |
handleChange = (event) => { | |
this.setState({[event.target.name]: event.target.value}); | |
} | |
handleSubmit = (event) => { | |
alert('A form was submitted: ' + this.state); | |
fetch('https://your-node-server-here.com/api/endpoint', { | |
method: 'POST', | |
// We convert the React state to JSON and send it as the POST body | |
body: JSON.stringify(this.state) | |
}).then(function(response) { | |
console.log(response) | |
return response.json(); | |
}); | |
event.preventDefault(); | |
} | |
render() { | |
return ( | |
<form onSubmit={this.handleSubmit}> | |
<label> | |
Name: | |
<input type="text" value={this.state.value} name="name" onChange={this.handleChange} /> | |
</label> | |
<input type="submit" value="Submit" /> | |
</form> | |
); | |
} | |
} |
h,fj,fyju
Huh?
He went nuts trying to understand the code.
lol
Thanks mate!
OMG this is so helpful! Thanks dude!
Thanks bro
thanks
Thanks 😊, but I tend to use stateless function components.
Could you please have an update for that?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
He went nuts trying to understand the code.