Error using AutoComplete of Material UI + react hook form - reactjs

I am using the component 'AutoComplete' of material Ui to render multiple Checkboxes, and show the options selected into a TextField.
The error occurs when I submit the form. The values of checkboxes selected are empty, like this: category: ""
It seems the react hook form is not recognizing the name "category", like below:
<Autocomplete
id="checkboxes-tags-demo"
fullWidth
multiple
limitTags={2}
getOptionLabel={(option) => option.title}
disableCloseOnSelect
noOptionsText="Nenhuma opção foi encontrada"
variant="outlined"
options={newCategories}
renderOption={(option, {selected}) => {
return (
<Box key={option.id} ml={option?.isSub ? 3 : 0}>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
checked={selected}
/>
{option.title}
</Box>
)
}
}
renderInput={(params) =>
<TextField
name="category"
inputRef={register}
{...params}
label="Selecione a categoria"
variant="outlined" />}
/>
}
/>

You need to wrap the Material UI Autocomplete with the Controller Component provided by React Hook Form. See this section in the documentation for further information.

Related

Material UI Autocomplete: Display part of selection

I'm displaying three property values (option.primary_line, option.city, option.state, and option.zip_code) from state in the autocomplete suggestions; however, I'm trying to display only the option.primary_line value in the textarea when an option from the list is selected. I've tried setting the option.primary_line value to state and adding it as a value (tried defaultValue as well) to the textarea to no avail. What am I missing?
<Autocomplete
id="combo-box-demo"
options={addressSuggestions}
getOptionLabel={(option) =>
`${option.primary_line}, ${option.city}, ${option.state} ${option.zip_code}`
}
onInputChange={handleAddressLookup}
freeSolo={true}
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
fullWidth
/>
)}
/>
You should use renderOption instead, and in getOptionLabel return the value you want to be assigned to the input
<Autocomplete
...
renderOption={(option) =>
`${option.primary_line}, ${option.city}, ${option.state} ${option.zip_code}`
}
getOptionLabel={(option) => option.primary_line}
...
/>

React material UI autocomplete is not working with the formik

I have this code snippet, which is written by someone else.
<FormControl className={classes.formControl}>
<InputLabel id="combo-box-demo">
{values.type === "forAllCustomers" ? "" : ""}
</InputLabel>
<Autocomplete
id="combo-box-demo"
name="customerId"
onBlur={handleBlur}
onChange={handleChange}
value={values.customerId}
options={agents}
getOptionLabel={(option) => option.name}
disabled={values.type === "forAllCustomers"}
renderTags={(value, getTagProps) => {
filteredAgents(values.type).map(
(option, agentId) => (
<Chip
variant="outlined"
label={option.name}
// size="small"
{...getTagProps({ agentId })}
/>
)
);
}}
renderInput={(params) => (
<TextF
{...params}
variant="outlined"
label="Customer"
placeholder="Select"
name="agentId"
/>
)}
/>
</FormControl>
Here we load bunch of agents. If user pick one agent, that agents id should set as the customerId.
Here we use formik, so onBlur={handleBlur} onChange={handleChange} is controlled by the formik.
I tried by setting value to values.customerId But it seems not working and also I am getting an error in the console saying
index.js:1 Material-UI: The getOptionLabel method of Autocomplete
returned undefined instead of a string for "".
How do I fix this issue?
Anyhelp!
Thanks in advance. =)
See, the signature of the function onChange of AutoComplete is:
function(event: object, value: T | T[], reason: string) => void
However, signature of handleChange of Formik is
handleChange: (e: React.ChangeEvent<any>) => void
The problem is that simply passing onChange={handleChange} will not do what you think.
See, if you put, before the return statement a console.log(values), you'll see your initialValues object. However, a change in the Autocomplete will fill this object with strange combo-box-demo-option-0 1, 2 and so on. This is because how the Autocomplete component handles the combobox and the name and id properties. According to Formik, handleChange will look for the name or id to operate, and none have the correspondence you want.
Enough said, to fix your problem, you have to use another method provided by Formik: setFieldValue
Your Autocomplete should look something on the lines of:
<Autocomplete
id="combo-box-demo"
name="customerId"
onChange={(e, v) => {
setFieldValue("name", v?.name || "");
setFieldValue("customerId", v?.id || "");
}}
value={values}
options={agents}
getOptionLabel={(option) => option.name || ''}
style={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label="Combo box" variant="outlined" />
)}
/>;
You will not need the useState because you are not handling yourself any state changes. A regular javascript object will be enough.
Please check the agents you are getting. There might be an issue with your agents data coming from API RESPONSE or from anywhere else. According to Material-UI, the parameter you pass to options should be in an Array but your one might be an Object.
Please convert the Data type of agents to Array instead of Object if it is not in an Array and it will work!
<Autocomplete
id="combo-box-demo"
name="customerId"
onBlur={handleBlur}
onChange={handleChange}
value={values.customerId}
options={agents} //This should be in An Array
getOptionLabel={(option) => option.name} //Then access name
disabled={values.type === "forAllCustomers"}
/>
Please check the Official Docs of Material-UI https://material-ui.com/components/autocomplete/

How to make autocomplete field of material UI required?

I have tried a couple of ways in order to make the material UI's autocomplete field of type required but I am not getting the behavior that I wanted. I had encapsulated my field inside react hook form <Controller/> yet no luck. I want to trigger message 'Field is mandatory' on submit when nothing is added to the field.
Below is the code snippet, I have not removed comments so that it becomes a bit easier for others to understand the approach that I had followed earlier -
<Controller
name="displayName"
as={
<Autocomplete
value={lists}
multiple
fullWidth
size="small"
limitTags={1}
id="multiple-limit-lists"
options={moduleList}
getOptionLabel={(option) => option.displayName}
renderInput={(params,props) => {
return (
<div>
<div className="container">
<TextValidator {...params} variant="outlined" label="Display Name*" className="Display Text"
name="displayName" id="outlined-multiline-static"
placeholder="Enter Display-Name" size="small"
onChange={handleDisplay}
// validators={['required']} this and below line does throw a validation but the problem is this validation stays on the screen when user selects something in the autocomplete field which is wrong.
// errorMessages={['This field is required']}
// withRequiredValidator
/>
</div>
</div>
)
}}
/>
}
// onChange={handleDisplay}
control={control}
rules={{ required: true }}
// required
// defaultValue={options[0]}
/>
<ErrorMessage errors={errors} name="displayName" message="This is required" />
You can use the following logic to get it worked. Though this might not be the best solution but works.
<Autocomplete
renderInput={(params) => (
<TextField
{...params}
label={value.length === 0 ? title : title + " *"} //handle required mark(*) on label
required={value.length === 0}
/>
)}
/>
I tried using the built in required in textfield for autocomplete, and it works like a charm. Maybe you can use this as a reference.
<Autocomplete
renderInput={(params) => {
<TextField {...params} required />
}
// Other codes
/>
Since you are rendering <TextValidator>, you should apply mandatory(required) attribute to that component not on <AutomComplete>.
Try this if your Material UI version is v5
<TextField
{...params}
required
label="Tags"
value={value}
InputProps={{
...params.InputProps,
required: value.length === 0,
}}
/>

Material UI : React Autocomplete component (controlled) and disableCloseOnSelect

I have a problem using the Autocomplete component provided by Material UI for React.js.
Here is what my component looks like :
<Autocomplete
options={options}
value={value}
disableCloseOnSelect
onChange={handleChange}
limitTags={4}
getOptionLabel={(option) => option.name }
renderOption={(option, { selected }) => (
<React.Fragment>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
className={classes.checkbox}
checked={selected}
/>
{option.name}
</React.Fragment>
)}
renderInput={(params) => (
<TextField {...params} variant="outlined" label={label} placeholder={label} />
)}
{...custom}
/>
I can't get the feature disableCloseOnSelect to function with a controlled component, as it does not prevent the list from closing after select... If I remove the props value and onChange everything works perfectly, but I need them for my project.
Does anybody have the same problem or see anything wrong with the way I am handling things ?
There is an issue that seems to match mine here. In that case, could it be a bug ?
This is most probably caused by the mother component re-rendering. Autocomplete's state needs to be localised.
Here's a sandbox demonstration of the difference this makes:
https://codesandbox.io/s/priceless-wilson-zz59q?file=/src/App.js
It also has performance benefits.

How to select default option in Material-UI Autocomplete component dynamically?

I am looking for a way to pre-set a default option in a Autocomplete component, just when the ajax call completes loading the list of options.
So the use case would be this: when the user opens the page, in the background a list of options would be loaded into state from the ajax response. I want to select the first retrieved option from the list, as soon as it gets loaded. Currently, I just have a basic way to offer a list of options:
<Autocomplete
options={defaultProps.options}
getOptionLabel={option => option.name}
renderInput={params => (
<TextField {...params} variant="outlined" fullWidth />
)}
/>
but don't know to select the first one when it gets loaded.
I'm using useEffect to demonstrate an ajax request on component mount.
You can use the value property to set the value after the component has been rendered.
While waiting for the ajax request to resolve, you can use the loading prop to change the component mode to loading
const [options, setOptions] = useState([]);
const [def, setDef] = useState(null);
useEffect((()=>{
setTimeout(()=>{
const tempArr = [{name:'Subject'},{name:'Another Subject'}];
setOptions(tempArr);
setDef(tempArr[0]);
}, 1000);
}), []);
return (
<div className="App">
<h1>Autocomplete</h1>
{<Autocomplete
options={options}
loading={!def}
value={def}
getOptionLabel={option => option.name}
renderInput={params => (
<TextField {...params} variant="outlined" fullWidth />
)}
/>}
</div>
);
In latest version of Material UI theres an autoHighlight prop.
<Autocomplete
options={defaultProps.options}
getOptionLabel={option => option.name}
renderInput={params => (
<TextField {...params} variant="outlined" fullWidth />
)}
autoHighlight // add this
/>
See the API for Autocomplete

Resources