Reputation: 13
Started learning react hooks a while ago but I don't know much about React class based components. I might be asking for too much but could someone can help me rewrite this code into react hooks:
import React from 'react'
import axios, { post } from 'axios';
class SimpleReactFileUpload extends React.Component {
constructor(props) {
super(props);
this.state = {
file: []
}
this.onFormSubmit = this.onFormSubmit.bind(this)
this.onChange = this.onChange.bind(this)
this.fileUpload = this.fileUpload.bind(this)
}
onFormSubmit(e) {
e.preventDefault() // Stop form submit
this.fileUpload(this.state.file).then((response) => {
console.log(response.data);
})
}
onChange(e) {
this.setState({ file: [...e.target.files] })
console.log(typeof (this.state))
console.log(this.state)
}
fileUpload(file) {
const url = 'http://example.com/file-upload';
const formData = new FormData();
formData.append('file', file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
return post(url, formData, config)
}
render() {
return (
<form onSubmit={this.onFormSubmit}>
<h1>File Upload</h1>
<input type="file" multiple onChange={this.onChange} />
<button type="submit">Upload</button>
</form>
)
}
}
export default SimpleReactFileUpload
I am kind of desperate so any help would be much appreciated
Upvotes: 0
Views: 48
Reputation: 13
Here is the Code I tried:
import React, { useState } from "react";
import axios, { post } from 'axios';
const SimpleReactFileUpload = () => {
const [state, setState] = useState({
file: []
})
const onFormSubmit = (e) => {
e.preventDefault() // Stop form submit
console.log(state.file)
fileUpload(state.file).then((response) => {
console.log(response.data);
})
}
const onChange = (e) => {
setState({ file: e.target.files })
console.log(state)
}
const fileUpload = (file) => {
const url = 'http://example.com/file-upload';
const formData = new FormData();
formData.append('file', file)
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
return post(url, formData, config)
}
return (
<form onSubmit={onFormSubmit}>
<h1>File Upload</h1>
<input type="file" multiple onChange={onChange} />
<button type="submit">Upload</button>
</form>
)
}
export default SimpleReactFileUpload
I don't know if I am close or not. I am total beginner
Upvotes: 1