Reputation: 1741
I have a react component that has a form getting user input.. Instead of the regular submit button that sends the form data, I want to be able to write this data to a file so it can be used at a later time.
Can this be done using vanilla JS or is there a library that may be more helpful?
My handle submit method looks like this:
handleSubmit = e => {
e.preventDefault();
const data = JSON.stringify({
parameters: {
startTime: this.state.date,
selectors: this.state.selectors,
offset: this.state.offset,
"length.seconds": this.state.lengthSeconds,
"runtime.seconds": !this.state.checked
? this.state.runtimeSeconds
: undefined
}
});
console.log(data);
};
So normally this would send the data inside the form state to the URL I specify.
Let's say I want to take this data inside of the form state, instead of submitting, write it to a file.
handleSave = e => {
e.preventDefault();
const data = JSON.stringify({
parameters: {
startTime: this.state.date,
selectors: this.state.selectors,
offset: this.state.offset,
"length.seconds": this.state.lengthSeconds,
"runtime.seconds": !this.state.checked
? this.state.runtimeSeconds
: undefined
}
});
// write data to csv file here.
};
Is this possible to do? Is there a certain library that would be helpful here?
I have a codesandbox here with a larger demonstration of my component and form
Upvotes: 1
Views: 4818
Reputation: 2224
Try similar to below:
import React, { useState } from 'react'
export default () => {
const [formdata, setFormData] = useState({})
const onChange = event => setFormData({ ...formdata, [event.target.name]: event.target.value });
const downloadableData = encodeURIComponent(JSON.stringify(formdata, null, 2))
return <React.Fragment>
<form>
<input type="text" name="name" onChange={onChange} value={formdata.name || ''} />
<input type="text" name="address" onChange={onChange} value={formdata.address || ''} />
<input type="text" name="emailId" onChange={onChange} value={formdata.emailId || ''} />
</form>
<a href={`data:applicatiom/json,${downloadableData}`} download="formdata.json">Download Form Data</a>
</React.Fragment>
}
Upvotes: 0
Reputation: 20526
You could call the following function in your handleSave
function:
function download(filename, text){
var blob = new Blob([text], {type: "text/plain"});
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
}
download("text.txt", "file contents here...");
List of MIME types here: https://www.freeformatter.com/mime-types-list.html#mime-types-list
Upvotes: 1