Validations not triggered during on click on submit button - reactjs

I would like to display required, min 1 and max 5 validations in following fields in material-ui dialog. At the moment I have added for one field, but some how validation is not displaying during on click on submit button in dialog. Could someone please advise me on how can i fix the problem.
demo link added here:
https://codesandbox.io/s/tender-wood-3jrwu?file=/src/App.js
const App = () => {
const [rating, setRating] = useState({
ballshooting: "",
dribbling: "",
ballcontrol: "",
sprinting: "",
fitness: ""
});
const [ratingTotal, setRatingTotal] = useState(0);
const [open, setOpen] = React.useState(false);
const { handleSubmit, register, errors } = useForm();
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => (isMounted.current = false);
}, []);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
const onChange = e => {
e.persist();
const ratingValues = {
...rating,
[e.target.name]: e.target.value
};
setRating(ratingValues);
ratingCalculation(ratingValues);
};
const ratingCalculation = ratingValues => {
const {
ballshooting,
dribbling,
ballcontrol,
sprinting,
fitness
} = ratingValues;
const newTotal =
Number(ballshooting) +
Number(dribbling) +
Number(ballcontrol) +
Number(sprinting) +
Number(fitness);
const finalAvg = newTotal / 5;
setRatingTotal(finalAvg);
return ratingTotal;
};
return (
<form className="ratingForm">
<Button
className="playerRatingBtn"
onClick={() => handleClickOpen()}
variant="outlined"
color="primary"
>
Enter Player Rating
</Button>
<Dialog open={open} onClose={handleClose} aria-labelledby="skills-area">
<DialogTitle id="skills-area">Rate the skills of a player</DialogTitle>
<DialogContent>
<label>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="ballshooting"
label="Ball Shooting"
type="text"
fullWidth
min={1}
max={5}
ref={register({
required: "Soccer ball shooting skill is required !"
})}
/>
<span className="newsErrorTextFormat">
{errors.shooting && errors.shooting.message}
</span>
</label>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="dribbling"
label="Dribbling"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="ballcontrol"
label="Ball Control"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="sprinting"
label="Sprinting"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="fitness"
label="Fitness"
type="text"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="secondary">
Cancel
</Button>
<Button type="submit" onClick={() =>
handleClose(
handleSubmit(calculateAvgRating(ratingCalculation(rating)))
)
} color="primary">
Submit
</Button>
</DialogActions>
</Dialog>
</form>
);
};
export default App;

Related

How to update existing data from DB with react-hook-form

I'm creating an E-commerce like website, we upload products through the admin site.
I have Upload.tsx file like so:
...
import FormDetails from '#components/FormDetails';
const Upload: React.FC = () => {
const { register, handleSubmit, reset, unregister, watch, setValue } =
useForm<UploadFormState>();
const watchPacksOrWholesale = watch('packsOrWholesale');
const [uploadLoading, setUploadLoading] = useState<boolean>(false);
const [file, setFile] = useState<File | null>(null);
const [url, setUrl] = useState<string>('');
const [progress, setProgress] = useState<number>(0);
const [createdAt, setCreatedAt] = useState<Timestamp | null>(null);
const saveProduct = useProductStore((state) => state.saveProduct);
const isLoading = useProductStore((state) => state.isLoadingSave);
const handleProductSubmit: SubmitHandler<UploadFormState> = (data) => {
const newProductUpload = {
drinkName: data.drinkName,
description: data.description,
category: data.category,
price: Number(data.price),
url,
createdAt,
packsOrWholesale: data.packsOrWholesale,
packSize: data.packSize,
};
saveProduct(newProductUpload, reset, setFile);
};
return (
<>
<Text fontSize="xl" mb={5} fontWeight="semibold">
Upload Drinks
</Text>
<form onSubmit={handleSubmit(handleProductSubmit)}>
<FormDetails
register={register}
file={file}
progress={progress}
setFile={setFile}
setProgress={setProgress}
isRequired={true}
unregister={unregister}
watchPacksOrWholesale={watchPacksOrWholesale}
setValue={setValue}
/>
<ButtonGroup mt={4} spacing={2}>
<Button
size="sm"
isLoading={uploadLoading}
isDisabled={!file || progress === 100}
onClick={handleProductImageUpload}
>
Upload Image
</Button>
<Button
size="sm"
type="submit"
variant="solid"
// isDisabled={!file || progress === 0}
colorScheme="success"
isLoading={isLoading}
>
Save Product
</Button>
</ButtonGroup>
</form>
</>
);
};
export default Upload;
.....
FormDetails.tsx
import {
....
} from '#chakra-ui/react';
import { FileInput } from '#components/FormFields';
import { drinkCategoriesArray } from '#data/index';
import { FormDetailsProps } from '#interfaces/index';
import { useEffect, useState } from 'react';
import { Controller } from 'react-hook-form';
const FormDetails: React.FC<FormDetailsProps> = ({
....
}) => {
const [isPacksOrWholesale, setIsPacksOrWholesale] = useState<boolean>(
product?.packsOrWholesale || false
);
useEffect(() => {
if (watchPacksOrWholesale) {
register('packsOrWholesale', { required: true });
} else {
unregister('packsOrWholesale');
}
}, [register, unregister, watchPacksOrWholesale, isPacksOrWholesale]);
return (
<>
<SimpleGrid columns={{ base: 1, sm: 2 }} spacing={6} textAlign="left">
<FormControl>
<FormLabel fontSize="14px">Drink name</FormLabel>
<Input
{...register('drinkName', { required: isRequired })}
type={'text'}
placeholder="Meridian"
defaultValue={(showValue && product?.drinkName) || ''}
/>
</FormControl>
<FormControl>
<FormLabel fontSize="14px">Description</FormLabel>
<Input
{...register('description', { required: isRequired })}
type={'text'}
placeholder="Meridian wine is the best"
defaultValue={(showValue && product?.description) || ''}
/>
</FormControl>
<FormControl>
<FormLabel fontSize="14px">Select Category</FormLabel>
<Select
{...register('category', { required: isRequired })}
placeholder="Select category"
defaultValue={(showValue && product?.category) || ''}
>
{drinkCategoriesArray.map(({ drinkCategory, drink_id }) => (
<option key={drink_id} value={drinkCategory}>
{drinkCategory}
</option>
))}
</Select>
</FormControl>
<FormControl>
<FormLabel>
<FormLabel fontSize="14px">Select Product method</FormLabel>
<HStack>
<Text fontWeight={'semibold'}>Product in wholesale</Text>
<Switch
id="packs switch"
{...register('packsOrWholesale')}
colorScheme={'primary'}
size={'sm'}
fontWeight={'semibold'}
defaultChecked={showValue && product?.packsOrWholesale}
isChecked={isPacksOrWholesale}
onChange={() => setIsPacksOrWholesale(!isPacksOrWholesale)}
/>
<Text fontWeight={'semibold'}>Product in packs</Text>
</HStack>
</FormLabel>
</FormControl>
{isPacksOrWholesale ? (
<FormControl>
<FormLabel>
<FormLabel fontSize="14px">Select pack size</FormLabel>
<Select
{...register('packSize', {
required: true,
})}
placeholder="Select Pack Size"
defaultValue={(showValue && product?.packSize) || ''}
>
<option value="6 Packs">6 Packs</option>
<option value="12 Packs">12 Packs</option>
</Select>
</FormLabel>
</FormControl>
) : null}
<FormControl mt={'3px'}>
<FormLabel fontSize="14px">Price</FormLabel>
<Input
{...register('price', { required: isRequired })}
type="number"
placeholder="500 (in Dollars)"
defaultValue={(showValue && product?.price) || ''}
/>
</FormControl>
</SimpleGrid>
....
</Box>
</>
);
};
export default FormDetails;
.....
ProductEdit.tsx
import FormDetails from '#components/FormDetails';
import { useProductStore } from '#store/useProductStore';
const ProductEdit = forwardRef(({ product }: ProductType, ref) => {
const { id } = useParams<ProductParams>();
const { register, handleSubmit, watch, unregister, reset, setValue } =
useForm<UploadFormState>();
const watchPacksOrWholesale = watch('packsOrWholesale');
const [file, setFile] = useState<File | null>(null);
const [uploadLoading, setUploadLoading] = useState<boolean>(false);
const [url, setUrl] = useState<string>('');
const [progress, setProgress] = useState<number>(0);
const { isOpen, onOpen, onClose } = useDisclosure();
const editProduct = useProductStore((state) => state.editProduct);
const isLoading = useProductStore((state) => state.isLoadingEdit);
const handleProductUpdate: SubmitHandler<UploadFormState> = (data) => {
const newUpdate = {
drinkName: data.drinkName || product?.drinkName,
description: data.description || product?.description,
category: data.category || product?.category,
url: url || product?.url,
price: Number(data.price) || Number(product?.price),
packsOrWholesale: data.packsOrWholesale || product?.packsOrWholesale,
packSize: data.packSize || product?.packSize,
};
// editProduct(id, newUpdate, onClose, setFile);
console.log(newUpdate);
};
return (
<Box>
<IconButton
aria-label="edit-button"
size="sm"
colorScheme="secondary"
variant="ghost"
onClick={onOpen}
icon={<RiPencilLine size="18px" />}
/>
<Modal
isCentered
size="lg"
onClose={onClose}
isOpen={isOpen}
motionPreset="slideInBottom"
closeOnOverlayClick={false}
>
<ModalOverlay backdropFilter={'blur(5px)'} />
<ModalContent>
<ModalHeader>
Edit Product{' '}
<chakra.span color="success.700">{product?.drinkName}</chakra.span>?
</ModalHeader>
<ModalCloseButton size="sm" />
<form onSubmit={handleSubmit(handleProductUpdate)}>
<ModalBody>
<FormDetails
register={register}
file={file}
progress={progress}
setFile={setFile}
setProgress={setProgress}
showValue={true}
isRequired={false}
product={product}
unregister={unregister}
watchPacksOrWholesale={watchPacksOrWholesale}
setValue={setValue}
/>
</ModalBody>
<ModalFooter>
<ButtonGroup mt={4} spacing={2}>
<Button
isLoading={uploadLoading}
onClick={handleProductImageUpload}
isDisabled={!file || progress === 100}
size="sm"
>
Upload Image
</Button>
<Button
size="sm"
type="submit"
variant="solid"
isLoading={isLoading}
colorScheme="success"
>
Update Product
</Button>
</ButtonGroup>
</ModalFooter>
</form>
</ModalContent>
</Modal>
</Box>
);
});
export default ProductEdit;
I have a reusable component, called FormDetails. I use this component to get the data from the admin input and do an upload. Alternatively, I also use it for the ProductEdit component.
Everything works fine, except for the fact that,
in the FormDetails component, I want to use react-hook-form to manage the state of what renders. i.e if watchPacksOrWholesale is true, which is linked to the Switch component, the Select component which holds the packSize should show.
The ProductEdit component picks the existing Product from firebase and then on editing the product using react-hook-form if I disable the Switch component the value for the PackSize should be an empty string, meaning I don't want a packSize. I should be able to update the product on Firebase.
All I'm saying is that the Switch component does not update well.

React Hooks form OnSubmit makes Problems

Hey i cant find a solution why my code dosent work. When i trigger the button nothing happens, normally i want to display the data but nothing happend. My Code is in attachment.
if someone has an idde to solve the problem I would be very grateful.
I have looked at other posts but nothing helps with my Problem.
export default function FormDialog(props) {
const [open, setOpen] = React.useState(false);
const {
control,
formState: { errors },
setValue,
} = useFormContext();
let isError = false;
let errorMessage = "";
if (errors && errors.hasOwnProperty(name)) {
isError = true;
errorMessage = errors[name].message;
}
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
props.func();
};
const handleChange = (event) => {
props.setMenge(event.target.value);
};
React.useEffect(() => {
if (errors) {
console.log(errors);
}
}, [errors]);
return (
<>
<Button variant="contained" onClick={handleClickOpen}>
Umbuchen
</Button>
<Dialog open={open} onClose={handleClose}>
<DialogTitle>Umbuchung</DialogTitle>
<DialogContent>
<DialogContentText>
Bitte geben Sie die Menge ein die umgelagert werden soll!
</DialogContentText>
<Controller
control={control}
name={props.name}
render={({ field }) => (
<TextField
{...field}
label={props.label}
error={isError}
helperText={errorMessage}
autoFocus
margin="dense"
id="menge"
type="number"
fullWidth
variant="standard"
/>
)}
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Schließen</Button>
<Button variant="contained" color="primary" type="submit">
Umbuchen
</Button>
</DialogActions>
</Dialog>
</>
);
}
export default function Home() {
const [sEingang, setSEingang] = useState([]);
const [sLager, setSLager] = useState("");
const [menge, setMenge] = useState(0);
const context = React.useContext(AuthContext);
const { data: warendata } = useWaren(context.access_token);
const { data: lagerdata } = useGetLager(context.access_token);
const methods = useForm({
resolver: yupResolver(validationShema),
mode: "all",
});
const { getValues, reset, watch, handleSubmit } = methods;
const waren = watch("selWaren");
const { data: chargendata, refetch } = useChargen({
access_token: context.access_token,
lager: waren,
});
const { mutateAsync, isError: mutError, isLoading, isSuccess } = useAnlegen();
React.useEffect(() => {
async function getToken() {
const res = await context.setTokenSilently();
}
const interval = setInterval(() => {
getToken();
}, 30000);
return () => clearInterval(interval);
}, []);
const onSubmit = (data) => {
console.log("data: ", data);
};
return (
<>
<CssBaseline />
<ButtonAppBar name={"Wareneingänge"} back={false} onClick={reset} />
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)}>
<Grid
container
spacing={0}
direction="column"
alignItems="center"
justifyContent="center"
sx={{p: 2, m: 3}}
style={{ minHeight: "50vh", }}
>
<Grid item xs={3}>
<MySelect
formname={"selWaren"}
data={warendata}
name={"Wareneingänge"}
selected={sEingang}
setSelected={setSEingang}
reset={reset} />
</Grid>
<Grid item xs={3}>
<MySelect
formname={"selLager"}
data={lagerdata}
name={"Freie Lagerplätze"}
selected={sLager}
setSelected={setSLager} />
</Grid>
<Grid item xs={3}>
<MySelect
formname={"selChargen"}
data={chargendata}
name={"Freie Chargenplätze"}
selected={sLager}
setSelected={setSLager} />
</Grid>
<Grid item xs={3} sx={{ m: 3}}>
<FormDialog
func={onSubmit}
name={"selMenge"} />
</Grid>
</Grid>
</form>
</FormProvider>
</>
);
}
It looks like you've forgotten to add an onClick handler for the submit button here:
<Button variant="contained" color="primary" type="submit">
Umbuchen
</Button>
Something like this should work:
<Button onClick={() => props.func()} variant="contained" color="primary" type="submit">
Umbuchen
</Button>

Passing a function and parameters with onclick in react

i am trying to create a dynamic form where a user can enter the details of a guest list. I also want to be on every row a button called "email" where the user can click on it and an automatically generated email would be sent to the guest on that row. i have created the dynamic form and i have a fun a function that sends emails using (mailjs) what i cant do is pass the details of that particular row to the onlcick function so the email is sent to the right guest
my form code :
const useStyles = makeStyles((theme)=>({
root:{
"& .MuiTextField-root":{
margin: theme.spacing(1),
}
},
button:{
margin: theme.spacing(1)
}
}))
function Guests () {
const classes=useStyles()
const [inputFields, setInputField] = useState([
{firstName: "", lastName:"", email:"", rsvp:"", menue:""},
])
const handleSubmit =(e) =>{
e.preventDefault();
console.log("input fields", inputFields)
}
const handleChangeInput = (index, event) =>{
console.log(index, event.target.name)
const values =[...inputFields];
values[index][event.target.name] = event.target.value
setInputField(values)
}
const handleAddField = () =>{
setInputField([...inputFields,{firstName: "", lastName:"", email:"", rsvp:"", menue:""}])
}
const handleRemoveField =(index) =>{
const values = [...inputFields]
values.splice(index, 1)
setInputField(values)
}
return (
<Container>
<h1> Your Guest List</h1>
<form className={classes.root} onSubmit={handleSubmit}>
{inputFields.map((inputField, index)=>(
<div key={index}>
<TextField
name="firstName"
label="First Name"
value={inputField.firstName}
onChange={event => handleChangeInput(index, event)}
/>
<TextField
name="lastName"
label="Last Name"
value={inputField.lastName}
onChange={event => handleChangeInput(index, event)}
/>
<TextField
name="email"
label="Email"
value={inputField.email}
onChange={event => handleChangeInput(index, event)}
/>
<TextField
name="rsvp"
label="RSVP"
value={inputField.rsvp}
onChange={event => handleChangeInput(index, event)}
/>
<TextField
name="menue"
label="Menu Choice"
value={inputField.menue}
onChange={event => handleChangeInput(index, event)}
/>
<Button className={classes.button}
vareient="contained"
color="secondary"
>Send email</Button>
<IconButton
onClick={()=> handleRemoveField(index)}>
<RemoveIcon />
</IconButton>
<IconButton
onClick={() => handleAddField()}>
<AddIcon />
</IconButton>
</div>
))}
<Button
className={classes.button}
vareient="contained"
color="secondary"
type="submit"
onClick={handleSubmit}
endIcon={<Icon>save</Icon>}>
Save Guest List
</Button>
</form>
</Container>
)
}
export default Guests
my email function is :
function sendEmail (event){
event.preventDefault();
emailjs.sendForm(service,template,event.target,hero).then(res=>{
console.log(res)
alert("email sent thank you");
}).catch(err=> console.log(err));
}
Many thanks for you help

Jest/Enzyme: Mock function in Functional Component

I have a functional component in React. Here is the code
import React, { useState, Fragment } from "react";
import { makeStyles } from "#material-ui/core/styles";
import "./K8sIPCalculator.css";
import { initialState, checkBoxLabel } from "./FormMetaData";
import { checkPositiveInteger } from "./FormDataValidation";
const useStyles = makeStyles((theme) => ({
// Styles
}));
const K8sIPCalculator = (props) => {
const classes = useStyles();
let intialStateCopy = JSON.parse(JSON.stringify(initialState));
const [data, setData] = useState(intialStateCopy);
const handleCheckBox = (path, value) => {
const newData = { ...data };
if (path === "nodes" || path === "pods") {
if (!checkPositiveInteger(value)) {
newData[path].value = value;
newData[path].helperText = "It should be a positive integer!";
} else {
newData[path].value = value;
newData[path].helperText = "";
}
} else newData[path] = value;
setData(newData);
};
const calculate = () => {
// Does some calculation and update data state
};
const onSubmit = () => {
if (data.nodes.helperText !== "" || data.pods.helperText !== "") {
alert("Data is not correct");
return;
}
calculate();
};
const onReset = () => {
intialStateCopy = JSON.parse(JSON.stringify(initialState));
setData(intialStateCopy);
};
return (
<Fragment>
<h2 className="name">K8s IP Calculator</h2>
<form className={classes.formRoot}>
<Accordion
defaultExpanded={true}
classes={{ expanded: classes.expanded }}
>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
id="accordion1"
className={classes.summary}
>
<Typography className={classes.heading}>Results</Typography>
</AccordionSummary>
<AccordionDetails className="container">
<InputLabel className={classes.label}>
Total useable IPs required:
</InputLabel>
<TextField
disabled
className={classes.textDisabledInput}
id="ips-required-output"
variant="outlined"
value={data.total}
/>
<InputLabel className={classes.label} htmlFor="subnet-size-output">
Subnet Size required:
</InputLabel>
<TextField
disabled
className={classes.textDisabledInput}
id="subnet-size-output"
variant="outlined"
value={data.subnet_size}
/>
</AccordionDetails>
</Accordion>
<br />
<Accordion
defaultExpanded={true}
classes={{ expanded: classes.expanded }}
>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
id="accordion2"
className={classes.summary}
>
<Typography className={classes.heading}>K8s Details</Typography>
</AccordionSummary>
<AccordionDetails className="container">
<InputLabel className={classes.label}>Nodes:</InputLabel>
<TextField
size="small"
type="number"
onChange={(e) => handleCheckBox("nodes", e.target.value)}
className={classes.textInput}
id="nodes-input"
variant="outlined"
value={data.nodes.value}
helperText={data.nodes.helperText}
/>
<InputLabel className={classes.label} htmlFor="pods-input">
Pods:
</InputLabel>
<TextField
size="small"
type="number"
onChange={(e) => handleCheckBox("pods", e.target.value)}
className={classes.textInput}
id="pods-input"
variant="outlined"
value={data.pods.value}
helperText={data.pods.helperText}
/>
<div id="nodes-error"></div>
</AccordionDetails>
</Accordion>
<div className="button-container">
<Button
id="reset-button"
className="button"
variant="outlined"
color="primary"
size="small"
onClick={onReset}
startIcon={<UndoIcon />}
>
Reset
</Button>
<Button
id="submit-button"
className="button"
variant="contained"
color="primary"
size="small"
startIcon={<SaveIcon />}
onClick={onSubmit}
>
Submit
</Button>
</div>
</form>
</Fragment>
);
};
export default K8sIPCalculator;
Things, I am trying to test,
When input changes, I want to check if handleCheckBox function has been called
When submit button is called, I want to check if calculate function has been called
How can I call the setData function to update data through Jest/Enzyme
I tried something like this
const spy = jest.spyOn(K8sIPCalculator, "calculate");
But I got
Cannot spy the calculate property because it is not a function; undefined given instead
PS: I am able to assert data change after submit is called. But I want to check if calculate function is called.
const submit = wrapper.find("button#submit-button");
submit.simulate("click");
expect(wrapper.find("input#ips-required-output").props().value).toEqual(35);
expect(wrapper.find("input#subnet-size-output").props().value).toEqual(
"/26"
);

How can I pass email displaying in DialogContentText to axios put request

How can I pass ratePlyrEmail to calculateAvgRating() during on click on submit button.
The player email will displays randomly in the <Input type="hidden" name="playertorate" value={email} onChange={onChange}></Input> of DialogContentText every time when the user click on Enter Player Rating button. I have added onChange in the DialogContentText. Now I am getting only rating and loginUserEmail in server side.
const [ratePlyrEmail, setRatePlyrEmail] = useState({ playertorate: ''});
const [rating, setRating] = useState({
shooting: "",
dribbling: "",
ballcontrol: "",
sprinting: "",
fitness: ""
});
const [ratingTotal, setRatingTotal] = useState(0);
const onChange = e => {
e.persist();
const ratingValues = {
...rating,
[e.target.name]: e.target.value
};
setRating(ratingValues);
const rateEmailValue = {
...ratePlyrEmail,
[e.target.name]: e.target.value
}
setRatePlyrEmail(rateEmailValue);
ratingCalculation(ratingValues);
};
const ratingCalculation = ratingValues =>{
const {
shooting,
dribbling,
ballcontrol,
sprinting,
fitness
} = ratingValues;
const newTotal =
Number(shooting) +
Number(dribbling) +
Number(ballcontrol) +
Number(sprinting) +
Number(fitness);
const finalAvg = newTotal / 5;
setRatingTotal(finalAvg);
return ratingTotal ;
}
const calculateAvgRating = (rating) => {
const sendPlayerRating = async () => {
try {
const params = {
email: loginUserEmail,
};
const res = await axios.put('http://localhost:8000/service/playerrating', {ratingTotal:rating}, {params} );
if (res.data.success) {
//rest of code to continue here...
}
else {
console.log(res.data.message);
}
} catch (e) {
console.log(e.response.data.message);
}
}
sendPlayerRating();
};
<div className="container">
<div className="weeklycount_graph_section">
<div>
<Button className="playerRatingBtn" variant="outlined" color="primary" onClick={() => handleClickOpen(setRandPlayerRating())}>
Enter Player Rating
</Button>
<Dialog
open={open}
onClose={handleClose}
aria-labelledby="skills-area"
>
<DialogTitle id="skills-area">Rate the skills of a player</DialogTitle>
<DialogContent>
{
randPlayers.map(({email, name, photo}) =>(
<DialogContentText key="id">
<Avatar alt="player" src={photo}/>
<Input type="hidden" name="playertorate" value={email} onChange={onChange}></Input>
</DialogContentText>
))
}
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="shooting"
label="Shooting"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="dribbling"
label="Dribbling"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="ballcontrol"
label="Ball Control"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="sprinting"
label="Sprinting"
type="text"
fullWidth
/>
<TextField
autoFocus
onChange={onChange}
margin="dense"
name="fitness"
label="Fitness"
type="text"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="secondary">
Cancel
</Button>
<Button onClick={() => handleClose(calculateAvgRating((ratingCalculation(rating))))} color="primary">
Submit
</Button>
</DialogActions>
</Dialog>
</div>
</div>
</div>

Resources