19
rated 0 times
[
22]
[
3]
/ answers: 1 / hits: 136031
/ 6 Years ago, wed, october 31, 2018, 12:00:00
I've been running through a react file upload tutorial and want to add on to it. I'm trying to make it so when a user clicks the upload message the browser will prompt them saying Your file is being uploaded I'm not a frontend dev by any means so please forgive me if this question is super nooby. For some reason when I use this code, if you navigate to the web page the code in the function runs once, and then again on click. My intended use is to only run on click, any idea what I am doing wrong?
import React, { Component } from 'react'
import { Alert } from 'react-alert'
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
imageURL: '',
};
this.handleUploadImage = this.handleUploadImage.bind(this);
}
handleUploadImage(ev) {
ev.preventDefault();
const data = new FormData();
data.append('file', this.uploadInput.files[0]);
data.append('filename', this.fileName.value);
fetch('http://localhost:8000/upload', {
method: 'POST',
body: data,
}).then((response) => {
response.json().then((body) => {
this.setState({ imageURL: `http://localhost:8000/${body.file}` });
});
});
}
render() {
return (
<form onSubmit={this.handleUploadImage}>
<div>
<input ref={(ref) => { this.uploadInput = ref; }} type=file />
</div>
<div>
<input ref={(ref) => { this.fileName = ref; }} type=text placeholder=Enter the desired name of file />
</div>
<br />
<div>
<button onclick=myFunction()>Upload</button>
<script>
function myFunction() {
alert(Your file is being uploaded!)
}
</script>
</div>
<img src={this.state.imageURL} alt=img />
</form>
);
}
}
export default Main;
More From » node.js