#javascript #reactjs #material-ui
Вопрос:
Как вы можете видеть на картинке ниже, когда я зашел на эту страницу, она выглядела так, и это совершенно нормально, как я хочу
но когда я загружаю в изображение (используя dropzoneArea) пользовательский интерфейс материала, он становится похожим на этот, и все выпадающее меню будет в одной строке, а также вы увидите кнопку «Отправить», также измененную
uploadProduct.js
import React, { useState,useEffect } from "react"; import { useHistory, useLocation } from "react-router-dom"; import { Typography, Grid, Button, FormGroup, TextField, Select, MenuItem, InputLabel, FormControl, InputAdornment, Input, } from "@mui/material"; import "./styles.css"; import FileUpload from "../../utils/FileUpload"; import Axios from "axios"; import MuiPhoneNumber from "material-ui-phone-number"; import decode from "jwt-decode"; export const UploadProduct = (props) =gt; { const location = useLocation(); const history = useHistory(); const [Token_Id, setToken_Id] = useState(localStorage.getItem("token")) const [Title, setTitle] = useState(""); const [userId, setuserId] = useState(0); const [Description, setDescription] = useState(""); const [Price, setPrice] = useState(); const [Category, setCategory] = useState(""); const [perGiven, setperGiven] = useState(""); const [Phone, setPhone] = useState(""); const [Address, setAddress] = useState(""); const [Name, setName] = useState("") const [Images, setImages] = useState([]); const handleLogout = () =gt; { localStorage.removeItem("token"); history.push("/"); setName(""); props.showAlert("Logout Successfully", "success"); }; useEffect(() =gt; { const token = Token_Id; if (token) { const { exp, name, id } = decode(token); setuserId(id) setName(name); if (Date.now() gt;= exp * 1000) { handleLogout(); } } setToken_Id(localStorage.getItem("token")); }, [location]); const updateImages = (newImages) =gt; { setImages(newImages); }; const onSubmit = (event) =gt; { event.preventDefault(); if ( !userId || !Name || !Title || !Description || !Price || !Category || !perGiven || !Phone || !Address || !Images ) { return alert("fill all the fields first!"); } const variables = { userId: userId, userName: Name, title: Title, description: Description, category: Category, price: Price, rentType: perGiven, images: Images, phoneNumber: Phone, address: Address, }; Axios.post("/product/uploadProduct", variables).then((response) =gt; { if (response.data.success) { alert("Product Successfully Uploaded"); history.push("/"); } else { alert("Failed to upload Product"); } }); }; return ( lt;div className="parentDiv" style={{marginTop: "70px", paddingBottom: "10px" }} gt; lt;div style={{ maxWidth: "700px", margin: "2rem auto" }}gt; lt;div style={{ textAlign: "center", marginBottom: "2rem" }}gt; lt;Typography variant="h4"gt;Anything for rent?lt;/Typographygt; lt;/divgt; lt;FormGroupgt; {/* DropZone */} lt;FileUpload refreshFunction={updateImages} /gt; lt;br /gt; lt;TextField variant="standard" required fullWidth id="title" label="AD TITLE" name="title" value={Title} autoFocus onChange={(e) =gt; setTitle(e.target.value)} /gt; lt;br /gt; lt;TextField variant="standard" required fullWidth id="description" label="DESCRIPTION" name="description" value={Description} onChange={(e) =gt; setDescription(e.target.value)} /gt; lt;br /gt; lt;FormControl variant="standard" sx={{ m: 0, minWidth: 120 }}gt; lt;InputLabel id="demo-simple-select-label"gt; CHOOSE CATEGORY lt;/InputLabelgt; lt;Select labelId="demo-simple-select-label" label="CHOOSE CATEGORY" name="category" onChange={(e) =gt; { setCategory(e.target.value); }} className="input" style={{display: "flex", alignItems: "center"}} gt; lt;MenuItem value=""gt; lt;emgt;Nonelt;/emgt; lt;/MenuItemgt; lt;MenuItem value="Tools"gt;Toolslt;/MenuItemgt; lt;MenuItem value="Apparels"gt;Apparelslt;/MenuItemgt; lt;MenuItem value="Vehicles"gt;Vehicleslt;/MenuItemgt; lt;MenuItem value="Equipments"gt;Equipmentslt;/MenuItemgt; lt;MenuItem value="Footwear"gt;Footwearlt;/MenuItemgt; lt;/Selectgt; lt;/FormControlgt; lt;br /gt; lt;MuiPhoneNumber className="my-2" label="PHONE NUMBER" variant="standard" value={Phone} defaultCountry={"pk"} onChange={setPhone} /gt; lt;br /gt; lt;Grid container className="my-1"gt; lt;Grid itemgt; lt;InputLabel htmlFor="standard-adornment-amount"gt; SET A PRICE lt;/InputLabelgt; lt;Input id="standard-adornment-amount" required={true} value={Price} onChange={(e) =gt; { setPrice(e.target.value); }} startAdornment={ lt;InputAdornment position="start"gt;Rslt;/InputAdornmentgt; } /gt; {/* lt;TextField required fullWidth id="price" label="Price" name="price" value={Price} onChange={(e) =gt; {setPrice(e.target.value)}} variant="standard" /gt; */} lt;/Gridgt; lt;Grid item className="mx-2" alignItems="stretch" style={{ display: "flex" }} gt; lt;FormControl className="my-1" variant="standard" sx={{ m: 2, minWidth: 150 }} gt; lt;InputLabel id="demo-simple-select-standard-label"gt; Rent type lt;/InputLabelgt; lt;Select labelId="demo-simple-select-standard-label" id="demo-simple-select-standard" value={perGiven} onChange={(e) =gt; { setperGiven(e.target.value); }} label="rent type" gt; lt;MenuItem value=""gt; lt;emgt;Nonelt;/emgt; lt;/MenuItemgt; lt;MenuItem value="Day"gt;Daylt;/MenuItemgt; lt;MenuItem value="Week"gt;Weeklt;/MenuItemgt; lt;MenuItem value="Month"gt;Monthlt;/MenuItemgt; lt;/Selectgt; lt;/FormControlgt; lt;/Gridgt; lt;/Gridgt; lt;TextField className="my-2" variant="standard" required fullWidth id="address" label="ADDRESS" name="address" value={Address} onChange={(e) =gt; setAddress(e.target.value)} /gt; lt;Button className="my-3" variant="contained" onClick={onSubmit}gt; Submit lt;/Buttongt; lt;/FormGroupgt; lt;/divgt; lt;/divgt; ); };
FileUpload.js
import React, { useState } from "react"; import { DropzoneArea } from "material-ui-dropzone"; import Axios from "axios"; function FileUpload(props) { const [Images, setImages] = useState([]); const onDrop = (files) =gt; { let formData = new FormData(); const config = { header: { "content-type": "multipart/form-data" }, }; formData.append("file", files[0]); //save the Image we chose inside the Node Server Axios.post("/product/uploadImage", formData, config).then((response) =gt; { if (response.data.success) { setImages([...Images, response.data.image]); props.refreshFunction([...Images, response.data.image]); } else { alert("Failed to save the Image in Server"); } }); }; const onDelete = (image) =gt; { const currentIndex = Images.indexOf(image); let newImages = [...Images]; newImages.splice(currentIndex, 1); setImages(newImages); props.refreshFunction(newImages); }; return ( lt;div style={{ display: "flex", justifyContent: "space-between" }}gt; lt;DropzoneArea onDrop={onDrop} multiple={false} maxSize={5000000} showPreviewsInDropzone={false} gt; {({ getRootProps, getInputProps }) =gt; ( lt;div style={{ width: "300px", height: "240px", border: "1px solid lightgray", display: "flex", alignItems: "center", justifyContent: "center", }} {...getRootProps()} gt; lt;input {...getInputProps()} /gt; lt;/divgt; )} lt;/DropzoneAreagt; lt;div style={{ display: "flex", marginLeft: "10px", width: "350px", height: "250px", overflowX: "scroll", }} gt; {Images.map((image, index) =gt; ( lt;div onClick={() =gt; onDelete(image)}gt; lt;img style={{ minWidth: "200px", width: "220px", height: "230px" }} src={`http://localhost:5000/${image}`} alt={`productImg-${index}`} /gt; lt;/divgt; ))} lt;/divgt; lt;/divgt; ); } export default FileUpload;
As you can see in the UploadProduct.js i called the FileUpload component for uploading the files. If you find any error or bug please let me know and any suggestion will be helpfull TIA