React Material UI + Formik FieldArray Autocomplete control value stays same on remove - reactjs

I want use Formik's form validation and it actually works just fine, but I ran into some issues with selected value display in Autocomplete component. I Have created Add/Remove buttons to dynamically adjust how many rows are in my form. The bug occurs when I try to remove form row, the row below, behind scenes has proper values as displayed in DEBUG, but user's input displays value from deleted form row. I cannot figure out, how to display or handle this occurrence.
Form before removal,
Form after removal
<FieldArray name="actions"
render={arrayHelpers =>
values.actions.map((action, index) => (
<Grid item container spacing={1} justify="center" alignItems="center"
key={index}>
<Grid item xs={4}>
<Field
error={getIn(errors, `actions.${index}.suggestedAction`) &&
getIn(touched, `actions.${index}.suggestedAction`)}
helperText={<ErrorMessage
name={`actions.${index}.suggestedAction`}/>}
name={`actions.${index}.suggestedAction`}
id={`actions.${index}.suggestedAction`}
variant="outlined"
fullWidth
as={TextField}
label="Siūloma priemonė"
multiline
rows={3}
rowsMax={10}
/>
</Grid>
<Grid item xs={4}>
<Autocomplete
freeSolo
onBlur={handleBlur}
onChange={(e, value) => {
//If adding new
if (value && value.inputValue) {
setOpen(true);
setFieldValue(`actions.${index}.responsiblePerson`, value.inputValue)
} else if (value && value.id) {
//Selecting existing
setFieldValue(`actions.${index}.responsiblePerson`, value.id)
} else {
setFieldValue(`actions.${index}.responsiblePerson`, "")
}
}}
getOptionLabel={(option) => {
if (typeof option === 'string') {
return option;
}
if (option.inputValue) {
return option.inputValue;
}
return option.title;
}}
handleHomeEndKeys
clearText="Pašalinti"
noOptionsText="Tuščia..."
renderOption={option => option.title}
filterOptions={(options, params) => {
const filtered = filter(options, params);
if (params.inputValue !== '') {
filtered.push({
inputValue: params.inputValue,
title: `Pridėti "${params.inputValue}"`,
});
}
return filtered;
}}
renderInput={params => (
<TextField
{...params}
id={`actions.${index}.responsiblePerson`}
name={`actions.${index}.responsiblePerson`}
error={getIn(errors, `actions.${index}.responsiblePerson`) &&
getIn(touched, `actions.${index}.responsiblePerson`)}
helperText={<ErrorMessage
name={`actions.${index}.responsiblePerson`}/>}
onChange={handleChange}
variant="outlined"
label="Atsakingas asmuo"
placeholder="Vardenis Pavardenis"
/>
)}
options={top100Films}/>
</Grid>
<DateTimeUtilsProvider>
<Grid item xs={3}>
<Field
disableToolbar
as={KeyboardDatePicker}
variant="inline"
inputVariant="outlined"
format="yyyy-MM-dd"
id={`actions.${index}.deadline`}
name={`actions.${index}.deadline`}
error={getIn(errors, `actions.${index}.deadline`) &&
getIn(touched, `actions.${index}.deadline`)}
helperText={<ErrorMessage
name={`actions.${index}.deadline`}/>}
label="Įvykdymo terminas"
onChange={value =>
setFieldValue(`actions.${index}.deadline`, value)}
/>
</Grid>
</DateTimeUtilsProvider>
<Grid item xs={1}>
<ButtonGroup fullWidth orientation="vertical" size="medium">
<Button onClick={() => {
arrayHelpers.remove(index);
}}
disabled={values.actions.length === 1}
classes={removeButtonClasses}>
<HighlightOff/>
</Button>
<Button onClick={() => {
arrayHelpers.insert(index + 1, {
suggestedAction: "",
responsiblePerson: "",
deadline: Date.now()
})
}}
color="primary">
<AddCircleOutline/>
</Button>
</ButtonGroup>
</Grid>
</Grid>
))
}
/>
</Grid>

Instead of
arrayHelpers.insert()
I have used
arrayHelpers.push()
and its working fine for me.

I had this same problem. I was setting a value prop on the <Field> inside my renderInput.
<Autocomplete
renderInput={params => (
<Field {...params} component={TextField} value={values.myArray[index]} />
)}
/>
I was able to fix it by moving the value attribute to the Autocomplete.
<Autocomplete
value={values.myArray[index]}
renderInput={params => (
<Field {...params} component={TextField} />
)}
...
/>

This worked for me
const arrayValue = options.filter(
(item) => item.id === values[arrayName][index][name]);
And then I used the filtered option as my value in the Autocomplete component
<Autocomplete
name={name}
value={arrayValue.length > 0 ? arrayValue[0] : null}
options={options}
groupBy={(option) => option.group}
getOptionLabel={(option) => option.value}
isOptionEqualToValue={(option, value) => option?.id === value?.id}
defaultValue={defaultValueCheck()}
onChange={(_, value) => {
setFieldValue(`${arrayName}[${index}].${name}`, value?.id ?? "");
}}
renderInput={(params) => (
<TextField
{...params}
{...configTextField}
name={`${arrayName}[${index}].${name}`}
/>
)}
renderGroup={(params) => (
<li key={params.key}>
<GroupHeader>{params.group}</GroupHeader>
<GroupItems>{params.children}</GroupItems>
</li>
)}
/>
</>

Related

Dynamically adding or removing items within a react-hook-forms form and registering the inputs?

I'm trying to implement a rather complicated form that has and date picker and input which the user can add multiple of (or delete). That data then gets added to the overall form on submit. How do I get react-hook-forms to register that little dynamic faux form within the real form?
Here's the faux form inputs:
<AddPackagesStyle>
<Label htmlFor="addedPackages" label="Add Packages" />
<DatePicker
id="dateRange"
selected={startDate}
selectsRange
startDate={startDate}
endDate={endDate}
placeholderText="select dates"
onChange={onDateChange}
/>
<PackageInput
id="PackageSelect"
placeholder="Select Package"
type="text"
value={name}
// #ts-ignore
onChange={(e) =>
// #ts-ignore
setName(e.target.value)
}
/>
<ButtonContainer>
<button type="button" onClick={clearAll}>
Clear
</button>
<button
type="button"
// #ts-ignore
onClick={addPackage}
>
Add
</button>
</ButtonContainer>
</AddPackagesStyle>
These entries get added to an array in a useState hook:
const [addedPackages, setAddedPackages] = useState<any[]>([])
Then this gets rendered in JSX as the add packages:
<ContentSubscriptionWrapper>
{addedPackages.length !== 0 &&
addedPackages.map((addedPackage, idx) => (
// #ts-ignore
<>
<ContentSubscriptionColumn>
{addedPackage.name && addedPackage.name}
</ContentSubscriptionColumn>
<ContentSubscriptionColumn>
{addedPackage.startDate &&
addedPackage.startDate.toString()}
</ContentSubscriptionColumn>
<ContentSubscriptionColumn>
{addedPackage.endDate && addedPackage.endDate.toString()}
</ContentSubscriptionColumn>
<button type="button" onClick={() => removePackage(idx)}>
X
</button>
</>
))}
</ContentSubscriptionWrapper>
So before the form gets submitted, the 'add packages' has to be set. Where do I add the {...register} object to add to the larger form object for submission?
const {
control,
register,
handleSubmit,
formState: { errors },
} = useForm<any>()
const onSubmit = (data: any) => {
console.log(data)
}
I created a CodeSandbox trying to reproduce your use case and used Material UI to get it done quickly, but you should get the idea and can modify it with your own components.
you should let RHF handle all the state of your form
use RHF's useFieldArray for managing (add, remove) your packages/subscriptions - there is no need to use watch here
use a separate useForm for your <AddPackage /> component, this has the benefit that you will have form validation for this sub form (in case it should be a requirement that all fields of <AddPackage /> need to be required) - i added validation in the demo to demonstrate this
AddPackage.tsx
export const AddSubscription: React.FC<AddSubscriptionProps> = ({ onAdd }) => {
const {
control,
reset,
handleSubmit,
formState: { errors }
} = useForm<Subscription>({
defaultValues: { from: null, to: null, package: null }
});
const clear = () => reset();
const add = handleSubmit((subscription: Subscription) => {
onAdd(subscription);
clear();
});
return (
<Card variant="outlined">
<LocalizationProvider dateAdapter={AdapterDateFns}>
<Grid container spacing={1} p={2}>
<Grid item container spacing={1} xs={12}>
<Grid item xs={6}>
<Controller
name="from"
control={control}
rules={{ required: "Required" }}
render={({ field }) => (
<DatePicker
{...field}
label="From"
renderInput={(params) => (
<TextField
{...params}
fullWidth
error={!!errors.from}
helperText={errors.from?.message}
/>
)}
/>
)}
/>
</Grid>
<Grid item xs={6}>
<Controller
name="to"
control={control}
rules={{ required: "Required" }}
render={({ field }) => (
<DatePicker
{...field}
label="To"
renderInput={(params) => (
<TextField
{...params}
fullWidth
error={!!errors.to}
helperText={errors.to?.message}
/>
)}
/>
)}
/>
</Grid>
</Grid>
<Grid item xs={12}>
<Controller
name="package"
control={control}
rules={{ required: "Required" }}
render={({ field: { onChange, ...field } }) => (
<Autocomplete
{...field}
options={packages}
onChange={(e, v) => onChange(v)}
renderInput={(params) => (
<TextField
{...params}
label="Package"
fullWidth
error={!!errors.package}
helperText={errors.package && "Required"}
/>
)}
/>
)}
/>
</Grid>
<Grid item xs={12}>
<Stack spacing={1} direction="row" justifyContent="end">
<Button variant="outlined" onClick={clear}>
Clear
</Button>
<Button variant="contained" onClick={add} type="submit">
Add
</Button>
</Stack>
</Grid>
</Grid>
</LocalizationProvider>
</Card>
);
};
Form.tsx
export default function Form() {
const { control, handleSubmit } = useForm<FormValues>({
defaultValues: {
seats: "",
addOns: false
}
});
const { fields, append, remove } = useFieldArray({
control,
name: "subscriptions"
});
const onSubmit = (data) => console.log("data", data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Grid container spacing={2}>
<Grid item xs={12}>
<Box display="flex" justifyContent="end" gap={1}>
<Button variant="outlined">Cancel</Button>
<Button variant="contained" type="submit">
Save
</Button>
</Box>
</Grid>
<Grid item xs={12}>
<Controller
name="seats"
control={control}
render={({ field }) => (
<TextField {...field} fullWidth label="Seats" />
)}
/>
</Grid>
<Grid item xs={12}>
<AddSubscription onAdd={append} />
</Grid>
<Grid item xs={12}>
<List>
{fields.map((field, index) => (
<ListItem
key={field.id}
secondaryAction={
<IconButton
edge="end"
aria-label="delete"
onClick={() => remove(index)}
>
<DeleteIcon />
</IconButton>
}
>
<ListItemText
primary={field.package.label}
secondary={
<span>
{formatDate(field.from)} - {formatDate(field.to)}
</span>
}
/>
</ListItem>
))}
</List>
</Grid>
<Grid item xs={12}>
<Controller
name="addOns"
control={control}
render={({ field: { value, onChange } }) => (
<FormControlLabel
control={<Checkbox checked={!!value} onChange={onChange} />}
label="Add-ons"
/>
)}
/>
</Grid>
</Grid>
</form>
);
}

How to Set Value in React Material UI Fields

I have a message field that I need to type on. before that I have variable dropdown that I need to APPEND to the message field everytime I select on it. My problem is that its overriding it. I'm using formik and Material-UI in React.
CODESANDBOX
<Autocomplete
value={values.variable}
options={variables}
getOptionSelected={(option, value) => option === value}
getOptionLabel={(data) => data}
onChange={(e, value) => {
setFieldValue("variable", value);
setFieldValue("message", value);
}}
fullWidth
renderInput={(params) => (
<TextField
{...params}
name="variable"
size="small"
variant="outlined"
onBlur={handleBlur}
helperText={touched.variable ? errors.variable : ""}
error={touched.variable && Boolean(errors.variable)}
/>
)}
/>
You do overwrite the value every time you select something :).
If you want to append you need the old value of message as well.
<Autocomplete
value={values.variable}
options={variables}
getOptionSelected={(option, value) => option === value}
getOptionLabel={(data) => data}
onChange={(e, value) => {
setFieldValue("variable", value);
// append the value
setFieldValue("message", `${values.message} ${value}`);
}}
fullWidth
renderInput={(params) => (
<TextField
{...params}
name="variable"
size="small"
variant="outlined"
onBlur={handleBlur}
helperText={touched.variable ? errors.variable : ""}
error={touched.variable && Boolean(errors.variable)}
/>
)}
/>

How to display data from html response body on textfield or textArea in material UI reactjs?

I have a form. On clicking the 'Evaluate' button, I send a post request. The response of this request is JSON, which I need to display in textField named Output.
How to display data in 'Output' textField?
I just need to display data(which is json in this case) to the text field.
My text field looks like this:
const MyTextField = ({select, values, nullable, min, max, helpertext, ...props}) => {
const [field, meta] = useField(props);
return (
<TextField
select={!!select}
variant="outlined"
margin="dense"
//{...field}
//defaultValue={meta.initialValue}
value={field.value}
error={meta.touched && meta.error}
helperText={(meta.touched && meta.error) ? meta.error : helpertext}
onChange={field.onChange}
onBlur={field.onBlur}
InputProps={{inputProps: {min: min, max: max}}}
{...props}
>
{
values && nullable && values instanceof Array && <MenuItem ><em>None</em></MenuItem>
}
{
values && values instanceof Array && values.map((value, index) => {
return <MenuItem key={value} value={value}>{value}</MenuItem>
})
}
</TextField>
);
};
and form looks like this
return (
<Container fluid className="main-content-container px-4">
<Row noGutters className="page-header py-4">
<PageTitle sm="12" title="Transformer Tester Tool" subtitle="" className="text-center"/>
</Row>
<Paper id="connPageRoot" className={classes.testerRoot}>
<Formik onSubmit={submitEvaluate} initialValues={request}>
<Form>
<div>
<MyTextField
variant="outlined"
margin="dense"
id="json2JsonTransformationConfigDto.template"
name="json2JsonTransformationConfigDto.template"
label="JSLT template"
multiline={true}
rowsMax={4}
fullWidth={true}/>
</div>
<div>
<MyTextField
variant="outlined"
margin="dense"
id="inputs.0"
name="inputs.0"
label="Json payload to be tested"
multiline={true}
rowsMax={4}
fullWidth={true}
/>
</div>
<div className={classes.connPageButton}>
<Button type={"submit"} color="primary" variant="contained">Evaluate</Button> </div>
<div>
<MyTextField
variant="outlined"
margin="dense"
id="outputs.0"
name="outputs.0"
label="Output"
value={result}
multiline={true}
rowsMax={4}
fullWidth={true}
/>
</div>
</Form>
</Formik>
</Paper>
</Container>
);

Autocomplete hover not responding properly

I have created an Autocomplete component that rely on the selected value of the parent Autocomplete.
This working perfectly. When I type or hover in order to select then, both are working as expected.
const [hoverd, setHoverd] = useState(false);
const onMouseOver = () => setHoverd(true);
const onMouseOut = () => setHoverd(false);
<div onMouseOver={onMouseOver} onMouseOut={onMouseOut}>
<Card className={classes.paper} raised={hoverd}>
<Grid item>
<Autocomplete
id="filter-by"
className={classes.search}
options={filterBy}
value={filterByValue}
onChange={(event, newValue) => {
setFilterByValue(newValue)
}}
renderInput={(params) =>
<TextField {...params}
variant="outlined"
label="Search by: ?"
InputProps={{
...params.InputProps,
}}
/>}
/>
</Grid>
{filterByValue === 'Campaign' ? <Grid item>
<Autocomplete
id="filter-by-campaign"
className={classes.search}
options={campaignData}
getOptionLabel={(option) => option.campaign}
renderInput={(params) =>
<TextField {...params}
variant="outlined"
label="Search by: campaign"
/>}
/>
</Grid> : <div />}
When I am moving the code to a separate component then its not working. I can type but the hover option not working.
{filterByValue === 'Campaign' ? <FilterByCampaign /> : <div />}
const FilterByCampaign = () => {
return <Grid item>
<Autocomplete
id="filter-by-campaign"
className={classes.search}
options={campaignData}
getOptionLabel={(option) => option.campaign}
renderInput={(params) =>
<TextField {...params}
variant="outlined"
label="Search by: campaign"
/>}
/>
</Grid>
}
I don’t understand what is the different between this two.
Any idea ?
Thank you
Try passing your onMouseOver function to the child component as a prop and then to the input
{filterByValue === 'Campaign' ? <FilterByCampaign onMouseOver={onMouseOver} /> : <div />}
const FilterByCampaign = ({ onMouseOver }) => {
return <Grid item>
<Autocomplete
id="filter-by-campaign"
className={classes.search}
options={campaignData}
getOptionLabel={(option) => option.campaign}
onMouseOver={onMouseOver} // depending on what the onMouseOver does either here
renderInput={(params) =>
<TextField
{...params}
onMouseOver={onMouseOver} // or here
variant="outlined"
label="Search by: campaign"
/>}
/>
</Grid>
}

Can't add items to material-ui form

I got handed down a project from someone else and I need to add some items to a form created with react and material-ui. I can get text fields to work but if I try to add a dropdown, it doesn't hold the value when selected.
I followed the same conventions of adding the items to the form that the guy who created this form used.
I added a grid item with a formcontrol component inside of it. There was also defaultprops set with a "game" object inside, that had all of the form fields as properties. I added the new field items to there also.
Here is the whole form component because I'm not really sure where the problem actually is.
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import history from '~/utils/history';
import { FormControl, Button, TextField, Grid, MenuItem, FormHelperText } from '#material-ui/core';
import { DateTimePicker } from 'material-ui-pickers';
import gameState from '~/utils/enums';
import { dateTime } from '~/utils/formats';
import { getById, create, update, remove } from '~/services/games';
import { getAll as getLeagues } from '~/services/leagues';
import { getAll as getSeasons } from '~/services/seasons';
import { getAll as getTeams } from '~/services/teams';
const GameForm = ({ game, id }) => {
useEffect(() => {
console.log({ form, game });
});
const [edit, setEdit] = useState(false);
const [form, setForm] = useState(game);
const [error, setError] = useState('');
const [variant, setVariant] = useState('outlined');
const [leagues, setLeagues] = useState([]);
const [seasons, setSeasons] = useState([]);
const [teams, setTeams] = useState([]);
const [gametype, setGametype] = useState(1);
const gametypes = [
{ key: 0, value: 'Series Game' },
{ key: 1, value: 'Playoff' },
{ key: 2, value: 'Final' },
{ key: 3, value: 'Else' }
];
useEffect(() => {
getSeasons()
.then(({ data }) => {
setSeasons(data);
return getLeagues();
})
.then(({ data }) => {
setLeagues(data);
if (id) {
getById(id).then(({ data }) => setForm(data));
} else {
setEdit(true);
}
});
}, []);
useEffect(() => {
if (edit) {
setVariant('outlined');
} else {
setVariant('standard');
}
}, [edit]);
useEffect(() => {
if (form.league) {
getTeams({ leagues: [form.league] }).then(({ data }) => setTeams(data));
}
}, [form.league]);
useEffect(() => {
if (form.gametype) {
setGametype('Playoff');
}
}, [form.gametype]);
const handleChange = ({ target }) => {
let { name, value } = target;
setForm({
...form,
[name]: value
});
};
const handleDateChange = formInputName => {
const dateHandler = moment => {
setForm({
...form,
[formInputName]: moment ? moment.toDate() : null
});
};
return dateHandler;
};
const handleFormSubmit = () => {
if (!edit) {
setEdit(true);
} else {
new Promise(resolve => {
resolve(form._id ? update(form) : create(form));
})
.then(() => {
history.push('/games');
})
.catch(error => setError(error.response.data.error));
}
};
const handleDelete = () => {
if (window.confirm(`Delete permanently?`)) {
remove(id).then(() => history.goBack());
}
};
const handleCancel = () => {
if (edit && id) {
setEdit(false);
} else {
history.goBack();
}
};
return (
<Grid container spacing={8} justify="space-between">
<Grid item xs={12} md={6}>
<FormControl margin="normal" required fullWidth variant="outlined">
<TextField
required
select
id="season"
name="season"
label="Season"
variant={variant}
disabled={!edit}
value={form.season}
onChange={handleChange}
>
{seasons.map(option => (
<MenuItem key={option.name} value={option._id}>
{option.name}
</MenuItem>
))}
</TextField>
</FormControl>
</Grid>
<Grid item xs={12} md={6}>
<FormControl margin="normal" required fullWidth variant="outlined">
<TextField
required
select
id="league"
name="league"
label="League"
variant={variant}
disabled={!edit}
value={form.league}
onChange={handleChange}
>
{leagues.map(option => (
<MenuItem key={option.name} value={option._id}>
{option.name}
</MenuItem>
))}
</TextField>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormControl margin="normal" required fullWidth variant="outlined">
<DateTimePicker
required
id="start"
name="start"
label="Game starts"
variant={variant}
disabled={!edit || !form.season}
autoOk
ampm={false}
keyboard
clearable
minDate={form.season ? seasons.find(({ _id }) => _id === form.season).start : undefined}
minDateMessage="Cannot start before the season begins"
maxDate={form.season ? seasons.find(({ _id }) => _id === form.season).end : undefined}
maxDateMessage="Cannot start after the end of the season"
value={form.start}
onChange={handleDateChange('start')}
{...dateTime}
/>
<FormHelperText disabled={!form.season}>
{!form.season ? 'Select season first' : undefined}
</FormHelperText>
</FormControl>
</Grid>
<Grid item xs={12} md={6}>
<FormControl margin="normal" required fullWidth variant="outlined">
<TextField
required
select
id="home"
name="home"
label="Home team"
variant={variant}
disabled={!edit || !form.league}
helperText={!form.league ? 'Select league first' : undefined}
value={form.home}
onChange={handleChange}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
{teams
.filter(({ _id }) => _id !== form.away)
.map(option => (
<MenuItem key={option.name} value={option._id}>
{option.name}
</MenuItem>
))}
</TextField>
</FormControl>
</Grid>
<Grid item xs={12} md={6}>
<FormControl margin="normal" required fullWidth variant="outlined">
<TextField
required
select
id="away"
name="away"
label="Team away"
variant={variant}
disabled={!edit || !form.league}
helperText={!form.league ? 'Select league first' : undefined}
value={form.away}
onChange={handleChange}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
{teams
.filter(({ _id }) => _id !== form.home)
.map(option => (
<MenuItem key={option.name} value={option._id}>
{option.name}
</MenuItem>
))}
</TextField>
</FormControl>
</Grid>
<Grid item xs={12} md={6}>
<FormControl margin="normal" required fullWidth variant="outlined">
<TextField
required
select
id="gametype"
label=" Game type"
variant={variant}
disabled={!edit}
value={form.gametype}
onChange={handleChange}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
{gametypes.map(option => (
<MenuItem key={option.key} value={option.value}>
{option.value}
</MenuItem>
))}
</TextField>
</FormControl>
</Grid>
<Grid item xs={12} md={6}>
<FormControl margin="normal" required fullWidth variant="outlined">
<TextField
text
id="umpire"
label="Umpire"
variant={variant}
disabled={!edit || !form.league}
/>
</FormControl>
</Grid>
<Grid item xs={12} md={6}>
<FormControl margin="normal" required fullWidth variant="outlined">
<TextField
text
id="scorekeeper"
label="Scorekeeper"
variant={variant}
disabled={!edit || !form.league}
/>
</FormControl>
</Grid>
<Grid item xs={12} md={6}>
<FormControl margin="normal" required fullWidth variant="outlined">
<TextField
text
id="referee1"
label="Referee 1"
variant={variant}
disabled={!edit || !form.league}
/>
</FormControl>
</Grid>
<Grid item xs={12} md={6}>
<FormControl margin="normal" required fullWidth variant="outlined">
<TextField
text
id="referee2"
label="Referee 2"
variant={variant}
disabled={!edit || !form.league}
/>
</FormControl>
</Grid>
<Grid item xs={12} md={6}>
<FormControl margin="normal" required fullWidth variant="outlined">
<TextField
text
id="referee3"
label="Referee 3"
variant={variant}
disabled={!edit || !form.league}
/>
</FormControl>
</Grid>
<Grid item xs={edit && id ? 4 : 6}>
<Button variant="outlined" color="secondary" fullWidth onClick={handleCancel}>
{edit && id ? 'Cancel' : 'Back'}
</Button>
</Grid>
{edit && id ? (
<Grid item xs={4}>
<Button
type="submit"
variant="contained"
color="secondary"
fullWidth
onClick={handleDelete}
>
Delete
</Button>
</Grid>
) : null}
<Grid item xs={edit && id ? 4 : 6}>
<Button
type="submit"
variant="outlined"
color="primary"
fullWidth
onClick={handleFormSubmit}
>
{edit ? (id ? 'Save' : 'Create') : 'Edit Game'}
</Button>
</Grid>
{!edit ? (
<Grid item xs={12}>
<Button
variant="outlined"
color="primary"
fullWidth
onClick={() => {
history.push('/games/' + id + '/scores');
}}
>
EDIT SCORES
</Button>
</Grid>
) : null}
</Grid>
);
};
GameForm.defaultProps = {
game: {
season: '',
league: '',
start: null,
home: '',
away: '',
gametype: '',
umpire: '',
scorekeeper: '',
referee1: '',
referee2: '',
referee3: ''
}
};
GameForm.propTypes = {
//classes: PropTypes.object.isRequired,
game: PropTypes.object
};
export default GameForm;
I noticed that if I print the game object to the console, it only shows the old form items and not the new ones I added. The new items are: gametype, umpire, scorekeeper, referee1-3.
I've been trying to make this work for a few days already, so any help would really be appreciated.
you need onChange={handleChange} in those and you also need to provide the name as props
BTW, I highly recommend you to combine those useStates as one single state object
For example, an alternative banned multiple useState() calls in a component. You’d keep state in one object.
function Form() {
const [state, setState] = useState({
edit: '',
form: '',
error: '',
});
// ...
}
To be clear, Hooks do allow this style. You don’t have to split your state into a bunch of state variables (see doc).

Resources