Reputation: 336
Im trying to access the file from the form but it wont get the data for it. How can I do this in a react functional component. I hope someone can help me with this, Thanks. I have tried using event but that is null and I cant find how to do this in a functional component so I dont understand why this wont work.
import React, { useState } from "react";
import {
Grid,
Paper,
Avatar,
TextField,
Button,
Typography,
Link,
Input,
} from "@material-ui/core";
import UserIcon from "@material-ui/icons/AccountBox";
import axios from "axios";
const Register = () => {
const [username, getUsername] = useState("");
const [password, getPassword] = useState("");
const [email, getEmail] = useState("");
const [file, getFile] = useState([]);
const registerUser = () => {
const data = new FormData();
data.append("file", file);
data.append("userName", username);
data.append("password", password);
data.append("email", email);
axios
.post("http://localhost:9020/api/v1/user/register", data)
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
};
const paperStyle = {
padding: 20,
height: "70vh",
width: 280,
margin: "20px auto",
};
const avatarStyle = { backgroundColor: "#1bbd7e" };
const btnstyle = { margin: "8px 0" };
return (
<Grid>
<Paper elevation={10} style={paperStyle}>
<Grid align="center">
<Avatar style={avatarStyle}>
<UserIcon />
</Avatar>
<h2>Register for an account</h2>
</Grid>
<TextField
label="Username"
placeholder="Enter username"
fullWidth
required
onChange={() => getUsername()}
/>
<TextField
label="Password"
placeholder="Enter password"
type="password"
fullWidth
required
onChange={() => getPassword()}
/>
<TextField
label="Email"
placeholder="Enter Email"
type="text"
fullWidth
required
onChange={() => getEmail()}
/>
<Input type="file" required onChange={() => getFile()} />
<Button
type="submit"
color="primary"
variant="contained"
style={btnstyle}
fullWidth
onClick={() => registerUser()}
>
Sign Up
</Button>
<Typography>
{" "}
Already have an account<Link href="#"> Sign In</Link>
</Typography>
</Paper>
</Grid>
);
};
export default Register;
Upvotes: 2
Views: 711
Reputation: 2695
You are handling the file input incorrectly. Try changing the input like this:
<input
type="file"
value={file}
onChange={(e) => getFile(e.target.files[0])}
/>
Also, Change the file useState initialisation as :
const [file, getFile] = useState(null);
Upvotes: 2