Material UI Create with Image
how can I create a create form with image upload using Material UI
useFormuseFormuseFormuseForm@refinedev/react-hook-form@refinedev/react-hook-form@refinedev/react-hook-form``tsx
import { useState } from "react";
import axios from "axios";
import { Edit } from "@refinedev/mui";
import { Box, Input, Stack, Typography } from "@mui/material";
import { LoadingButton } from "@mui/lab";
import { HttpError } from "@refinedev/core";
import { useForm } from "@refinedev/react-hook-form";
import FileUploadIcon from "@mui/icons-material/FileUpload";
import { ICategory, IPost } from "interfaces";
import { TOKEN_KEY, API_URL } from "../../constants";
export const PostEdit: React.FC = () => {
const [isUploadLoading, setIsUploadLoading] = useState(false);
const [imageURL, setImageURL] = useState("");
const {
saveButtonProps,
register,
formState: { errors },
setValue,
setError,
} = useForm<IPost, HttpError, IPost & { category: ICategory; cover: any }>();
const onChangeHandler = async (
event: React.ChangeEvent<HTMLInputElement>,
) => {
try {
setIsUploadLoading(true);
const formData = new FormData();
const target = event.target;
const file: File = (target.files as FileList)[0];
formData.append("files", file);
const res = await axios.post(, formData, {
headers: {
Authorization: ,
},
});
setImageURL(BoxBoxInputStackTypographyLoadingButtononChangeHandleronChangeHandlerformStatesetErrorFormDataFormDataFormDataFormDataFormDataappendtitledescriptiongetValues "id": 46,
"name": "my attachment",
"image": "http://localhost/media/upload_to/orange.png",
"type": null,
"performance": 44,import { Create } from "@refinedev/mui";
import { Box, TextField } from "@mui/material";
import { useForm } from "@refinedev/react-hook-form";
export const MyCreate = () => {
const {
saveButtonProps,
refineCore: { formLoading },
register,
control,
formState: { errors },
} = useForm();
return (
<Create isLoading={formLoading} saveButtonProps={saveButtonProps}>
<Box
component="form"
sx={{ display: "flex", flexDirection: "column" }}
autoComplete="off"
>
// all my existing field goes here
<TextField/>........
</Box>
</Create>
);
};``tsx
import { Create } from "@refinedev/mui";
import { Box, TextField, Button } from "@mui/material";
import { useForm } from "@refinedev/react-hook-form";
import { useState } from "react";
import { useApiUrl } from "@refinedev/core";
export const MyCreate = () => {
const apiUrl = useApiUrl();
const [imageUrl, setImageUrl] = useState("");
const {
saveButtonProps,
refineCore: { formLoading, onFinish },
register,
control,
formState: { errors },
setValue,
} = useForm();
const handleImageUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
const formData = new FormData();
formData.append("file", file);
try {
const response = await fetch(handleImageUploadhandleImageUpload${apiUrl}/media/upload${apiUrl}/media/uploadhandleSubmithandleSubmithandleSubmit<http://localhost/media/upload_to/orange.pngsetValuehandleImageSelectonFinishMyCreate``
The key changes in this corrected version are:
1. We use the function from to get all the form values.
2. The function now correctly receives an event of type .
3. We prevent the default form submission behavior using .
4. We create a object and populate it with the form values obtained from .
5. The now uses an arrow function to call with the correct event type.
This approach ensures that we correctly get all the form data, including the file input, and send it as a single object to the server.
[React Hook Form Validation with Complete Examples](<https://refine.dev/blog/react-hook-form-validation-examples/#form-submission>)
Remember to adjust your data provider or API client to handle sending const onChangeHandler = async (
event: React.ChangeEvent<HTMLInputElement>,
) => {
try {
setIsUploadLoading(true);
const formData = new FormData();
const target = event.target;
const file: File = (target.files as FileList)[0];
formData.append("files", file);
// Add additional body data
formData.append("title", "Your title here");
formData.append("description", "Your description here");
// Add more fields as needed
const res = await axios.post(`${API_URL}/api/upload`, formData, {
headers: {
Authorization: `Bearer ${localStorage.getItem(TOKEN_KEY)}`,
"Content-Type": "multipart/form-data", // Ensure this header is set
},
});
setImageURL(`${API_URL}${res.data[0].url}`);
setValue("cover", res.data[0].id, { shouldValidate: true });
setIsUploadLoading(false);
} catch (error) {
setError("cover", { message: "Upload failed. Please try again." });
setIsUploadLoading(false);
}
};