Last active
May 2, 2019 10:35
-
-
Save everdimension/c74953456fd8a533b252508d4738733e 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
class MyForm extends React.Component { | |
constructor() { | |
super(); | |
this.handleSubmit = this.handleSubmit.bind(this); | |
} | |
handleSubmit(event) { | |
event.preventDefault(); | |
const data = new FormData(event.target); | |
fetch('/api/form-submit-url', { | |
method: 'POST', | |
body: data, | |
}); | |
} | |
render() { | |
return ( | |
<form onSubmit={this.handleSubmit}> | |
<label htmlFor="username">Enter username</label> | |
<input id="username" name="username" type="text" /> | |
<label htmlFor="email">Enter your email</label> | |
<input id="email" name="email" type="email" /> | |
<label htmlFor="birthdate">Enter your birth date</label> | |
<input id="birthdate" name="birthdate" type="text" /> | |
<button>Send data!</button> | |
</form> | |
); | |
} | |
} |
@thorstensson This example is only the front-end. You'll need to set up that route to accept the data in your preferred server side language. Here's a node example.
const express = require('express');
const app = express();
app.post('/api/add-user', (req, res) => {
console.log(req.body);
});
app.listen(process.env.PORT || 8080, () => console.log(`Listening on port ${process.env.PORT || 8080}!`));
Just a heads up, node's body-parser
package doesn't support FormData being sent from the front-end.
I needed to JSON.stringify the body and pass a JSON header, like:
fetch('/api/add-user', {
method: 'post',
body: JSON.stringify({
name: data.get('name'),
email: data.get('email'),
country: data.get('country')
}),
headers:{
'Content-Type': 'application/json'
}
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Stupid question from someone that used to do this with php. But how do you actually get the data sent to an actual email adress. And where are your imports?
I am staring at
fetch('/api/form-submit-url'
So, form-submit-url can be found eh where?
Looking at compatibility, this is chrome/mozilla bound...which is great. But think I have to do some research into an allround solution since some folks sadly contact me from IE.
Thanks in advance.