How to Set Value in React Material UI Fields - reactjs

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)}
/>
)}
/>

Related

Autocomplete won't show a value and let me set a new one

I'm using material UI Autocomplete and react-hook-form to build a modal, but I simply can't show a value and change it at the same time.
When I pass the “default” value to InputValue, it does show up on the screen, but I can't edit it via input, and when I place it down on value it won't show on the screen, but it does let me change values via input and select.
This would be my component that is being rendered
<Autocomplete
id={name}
options={options}
getOptionLabel={(option) => (option.descricao ? option.descricao : "")}
filterOptions={filterOptions}
onChange={(e, options) =>
// console.log(options)
setValue(name, options?.descricao)
}
// onInputChange={(e, v) => setValue(name, v)}
value={cnae ? cnae : ""}
inputValue={cnae ? cnae : ""}
renderOption={(props, options) => (
<Box component="li" {...props}>
{options.id +
"/" +
options.grupo.divisao.id +
", " +
options.descricao}
</Box>
)}
loading={loading}
renderInput={(params) => (
<TextField
{...params}
{...other}
label={label}
error={Boolean(errors[name])}
helperText={errors[name] ? errors[name].message : ""}
/>
)}
/>
This are the what props are being passed:
<ACCnae
name="cnae"
label="Ramo"
fullWidth
errors={errors}
options={context.cnae}
setValue={setValue}
cnae={getValues("cnae")}
required
/>
And as you can tell here, i'm typing, but only clearing and selecting works
I've found a way to make it work, but it's definitely not the right way or the best way to do it.
First I find the whole object that I need to set as the value on the autocomplete, that's the only way to actually make it work.
And if the object is already set I use the setValue from react-hook-form to set the new value to the data object.
React.useEffect(() => {
if (!obj) {
setObj(options.find((item) => item.descricao === cnae));
}
if (obj?.descricao) {
setValue(name, obj.descricao);
}
}, [cnae, obj]);
And the only thing that I've changed from the previous component is that now onChange actually takes setObj
<Autocomplete
id={name}
options={options}
getOptionLabel={(option) => option?.descricao}
filterOptions={filterOptions}
onChange={(e, options) => setObj(options)}
value={obj ? obj : ""}
renderOption={(props, options) => (
<Box component="li" {...props}>
{options.id +
"/" +
options.grupo.divisao.id +
", " +
options.descricao}
</Box>
)}
loading={loading}
renderInput={(params) => (
<TextField
{...params}
{...other}
label={label}
error={Boolean(errors[name])}
helperText={errors[name] ? errors[name].message : ""}
/>
)}
/>
If anyone finds a better or simpler way to do it pls let me know

I can't get new value from autocomplete react

I am using autocomplete of material UI in my react app, I want to get the value when I change the item but I am getting undefined.
Here is my code
<Controller
name="partnerId"
control={control}
defaultValue={[]}
render={({ field: { onChange, value } }) => (
<Autocomplete
id="filter-demo"
className="mt-8 mb-16"
defaultValue={personObj}
value={value}
onChange={(newValue) => {
console.log('value...', newValue)
onChange(newValue);
}}
variant="outlined"
options={partners}
getOptionLabel={option => option.name}
filterOptions={filterOptions}
renderInput={params => <TextField {...params} label="Partners" variant="outlined" />}
/>
)}
/>
Try onchange as
onChange={(event,newValue) => {
console.log('value...', newValue)
onChange(newValue);
}}

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

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>
)}
/>
</>

A component is changing an uncontrolled Autocomplete to be controlled

Can you tell me that why I'm getting error "A component is changing an uncontrolled Autocomplete to be controlled.
Elements should not switch from uncontrolled to controlled (or vice versa).
Decide between using a controlled or uncontrolled Autocomplete element for the lifetime of the component."
component :
function AutoComplete(props) {
const defaultProps = {
options: props.options,
getOptionLabel: option => option.name,
};
const handleChange = (e, value) => {
props.onChange(value);
};
return (
<Autocomplete
{...defaultProps}
renderInput={params => (
<TextField {...params} label={props.label} margin="normal" />
)}
onChange={handleChange}
value={props.value}
/>
);
}
calling autocomplte:
<Controller
control={control}
name = 'country'
as = {
<AutoComplete
options={countryOptions}
onChange={selectCountryHandler}
label="Country"
value={selectedCountry || ''}
/>
} />
how can I solve this error?
You ensured that the value property never had been undefined, but you had to do same for inputValue.
the "value" state with the value/onChange props combination. This state represents the value selected by the user, for instance when pressing Enter.
the "input value" state with the inputValue/onInputChange props combination. This state represents the value displayed in the textbox.
⚠️ These two state are isolated, they should be controlled independently.
Component becomes uncontrolled when inputValue property is undefined, and vice versa.
If in the following example you delete an empty string from
React.useState('') you'll get the same error message because inputValue during first render is undefined.
import React from 'react'
import TextField from '#material-ui/core/TextField'
import Autocomplete from '#material-ui/lab/Autocomplete'
const options = ['Option 1', 'Option 2']
export default function AutocompleteLab() {
const [value, setValue] = React.useState(options[0])
const [inputValue, setInputValue] = React.useState('')
return (
<div>
<div>{`value: ${value !== null ? `'${value}'` : 'null'}`}</div>
<div>{`inputValue: '${inputValue}'`}</div>
<br />
<Autocomplete
value={value}
onChange={(_, newValue) => {
setValue(newValue)
}}
inputValue={inputValue}
onInputChange={(_, newInputValue) => {
setInputValue(newInputValue)
}}
options={options}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Name" variant="outlined" />}
/>
</div>
)
}
When no value is selected, you need to add || null to prevent the Autocomplete going into uncontrolled mode:
<Autocomplete {...props} value={props.value || null} />
If you pass value={undefined} to the Autocomplete component, it will start in "uncontrolled" mode, meaning it keeps its own internal state. Then if you later supply a value it raises the "A component is changing" error. But if you pass value={null}instead of value={undefined} that causes the Autocomplete to start in controlled mode. The Autocomplete will assume you will be providing the state, not keep its own, and the error goes away.
I solved this by removing the default value.
<Autocomplete
multiple
id="multiple-limit-tags"
options={(option) => option.label}
getOptionLabel={(option) => option}
// defaultValue={options || []}
renderInput={(params) => <TextField {...params} label="My Label" />}
/>
It wasn't obvious how to solve this, and the documentation doesn't help much either. I find it curious that a copy-pasted example from the documentation results in this error. I guess the example works because the choices are hard-coded.
Previous answer was absolutely correct, BUT I spend 20 minutes while I figure out that inputValue it should be value
So working example from me:
export default function AddModal(): ReactElement {
const [resource, setResource] = useState('one');
<Autocomplete
id="autocomplete"
options={['one', 'two']}
defaultValue={resource}
value={resource}
PopperComponent={StyledPopper}
onChange={(event, newInputValue) => setResource(newInputValue)}
renderInput={(params) => <TextField {...params} />}
/>
I had the same issue today, but I was able to solve it by providing a default value of null as well as providing a null value in case of it not existing. I'll leave the code that worked for me:
<Autocomplete
value={filters.tag || null}
defaultValue={null}
options={tags || []}
getOptionLabel={(option) => option}
renderInput={(params) => (
<TextField {...params} label="Search" variant='outlined' size='small' />
)}
fullWidth
onChange={(event, value) => {
if (value) {
setFilters({ ...filters, tag: value });
} else {
setFilters({ ...filters, tag: '' });
}
}}
/>
For me I fixed this issue by updated the onChange function and add || null rather then removing the default value since I still need it here is the code
<Box mt={2}>
<Controller
control={control}
name="thematic"
rules={{
required: 'Veuillez choisir une réponse',
}}
render={({ field: { onChange } }) => (
<Autocomplete
defaultValue={
questionData?.thematic ? questionData?.thematic : null
}
options={thematics}
getOptionLabel={(option) => option.name}
onChange={(event, values) => {
onChange(values || null)
}}
renderInput={(params) => (
<TextField
{...params}
label="Thématique"
placeholder="Thématique"
helperText={errors.thematic?.message}
error={!!errors.thematic}
/>
)}
/>
)}
/>
</Box>
For the autocomplete with options which is a simple array without object you can simply do it that way and u want get any issue
<Box mt={2}>
<Controller
control={control}
name="type"
rules={{
required: 'Veuillez choisir une réponse',
}}
render={({ field: { onChange, value } }) => (
<Autocomplete
freeSolo
options={['Champ', 'Sélection', 'Choix multiple']}
onChange={(event, values) => onChange(values)}
value={value}
renderInput={(params) => (
<TextField
{...params}
label="Type de la question"
variant="outlined"
onChange={onChange}
helperText={errors.type?.message}
error={!!errors.type}
/>
)}
/>
)}
/>
</Box>
the default value you can set it within useForm if you are using react-hook-form
const {
handleSubmit,
control,
watch,
register,
formState: { errors },
} = useForm({
defaultValues: {
...
type: questionData?.type ? mapperQuestionType[questionData?.type] : '',
},
})

react- cleaning autocomplete generates an error

I have a form created with material-ui, I have a textfield that uses autocomplete which is filled with a useEffect that is responsible for bringing the data from the API to load the AUTOCOMPLETE.
The data is not saved.
Code
const defaultProps={
options:location.name,
getOptionLabel: option => option.label + "-" + option.phone,
};
<Autocomplete
style={{ width: 300 }}
{...defaultProps}
id="city"
autoComplete
onChange={(event, newVal)=>onChange({target:{name:"name",value: newVal.label }}
)}
renderInput={params => (
<TextField {...params} label="Country" margin="normal" variant="outlined" inputProps={{
...params.inputProps,
}}/>
)}
What is causing that behavior?
It appears your problem in on the following line:
onChange={(event, newVal)=>onTagsChange({target:{name:"label",value: newVal.label }}
It may be related to newValue being null after clearing. You could add a protection such as:
value: newVal || newVal.label
Since it is not clear to me how you are using the resulting selection my suggested protection may not be appropriate.
You may also want to take a look at their "controlled" example in the documentation (https://material-ui.com/components/autocomplete/#playground) in which they use the value attribute to control the AutoComplete:
<Autocomplete
{...defaultProps}
id="controlled-demo"
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
renderInput={params => (
<TextField {...params} label="controlled" margin="normal" fullWidth />
)}
/>

Resources