-
-
Save everdimension/c74953456fd8a533b252508d4738733e to your computer and use it in GitHub Desktop.
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> | |
); | |
} | |
} |
@stevenkaspar No, not really. According to fetch
spec, body can be an instance of FormData
: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Body
The point of this example is that you do not need to explicitly specify all the data field when the form is submitted. You just say "send the fields and values of this form".
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.
@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'
}
});
To get this fully working you need to add the
get(fieldName)
s, correct?