Skip to content

Instantly share code, notes, and snippets.

@Sparragus
Last active April 17, 2023 19:25
Show Gist options
  • Save Sparragus/2760b5c393c9d0ad9657 to your computer and use it in GitHub Desktop.
Save Sparragus/2760b5c393c9d0ad9657 to your computer and use it in GitHub Desktop.
A react component that sends form data in json format.
var React = require('react');
// JSONFormData - https://github.com/roman01la/JSONFormData
// Only works on the browser.
require('../../vendor/JSONFormData/src/json-formdata');
var JSONForm = React.createClass({
propTypes: {
method: React.PropTypes.string.isRequired,
action: React.PropTypes.string.isRequired
},
handleSubmit: function(e) {
e.preventDefault();
const form = e.target;
const formData = JSON.stringify(new JSONFormData(form).formData);
console.log(formData);
// const xhr = new XMLHttpRequest();
// xhr.open(form.method, form.action);
// xhr.setRequestHeader('Content-Type', form.enctype);
// xhr.send(formData);
// xhr.addEventListener('loadend', function() {
// }, false);
},
render: function() {
const { action, method, ...other } = this.props;
const formProps = {
...other,
method,
action,
encType: 'application/json',
onSubmit: this.handleSubmit
};
return (
<form {...formProps}>
{this.props.children}
</form>
);
}
});
module.exports = JSONForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment