React: Why does autocomplete unintentionally reset the selected value? - javascript

Good evening, i'm trying to solve a problem where the autocomplete value is reset. This happens when i'm changing the state of the UI (example in sandbox). I want the value to still be there, if a user decided to go back and change it. I don't why the autcomplete react that way, but I haven't found a solution.
Any suggestions how to solve this?
Link: https://codesandbox.io/s/sharp-diffie-6ikc6?file=/index.js

You should use controlled version of the autocomplete. The issue is caused by onInputChange callback, which fired not just for selecting option. In your case React removes the autocomplete from DOM (because of your switch) and it fires onInputChange with empty value, so your state changes to empty string.
To avoid this you should use value and onChange instead. onChange fires only if you change the option.
const [value, setValue] = useState(null);
<Autocomplete
value={value}
disablePortal
id="combo-box-demo"
options={movies.sort(
(a, b) => -b.distributor.localeCompare(a.distributor)
)}
onChange={onInputChange}
groupBy={(option) => option.distributor}
getOptionLabel={(option) => option.movie}
sx={{ width: "100%", paddingRight: 2 }}
renderInput={(params) => (
<TextField
style={{ backgroundColor: "#fff", marginLeft: 25 }}
{...params}
label="Movie"
/>
)}
selectOnFocus={false}
/>
Check it out: https://codesandbox.io/s/peaceful-shamir-r2dwi?file=/index.js

Related

MUI Autocomplete component showing two clear buttons in Chromium. How to hide both?

The second clear button shows only on Chromium; it doesn't show on Firefox.
Example of a MUI React Autocomplete component showing two clear buttons.
All the solutions mentioned here hide only the right most button, not the one on the left.
How do I hide the one on the left?
This seems to happen only when type: 'search' is added to InputProps
Minimal, reproducible example on Chromium Version 110.0.5481.100:
<Autocomplete
disablePortal
disableClearable
id="combo-box-demo"
options={supported_games}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Movie" InputProps={{ ...params.InputProps, type: 'search'}} />}
/>

How to style list option in Autocomplete material ui with use of renderOption?

I am trying hard to customize option elements in autocomplete list. I want to do this by use of renderOptions prop, where i can create DOM elements. Then, i can pretty easly add styles with sx or styled components.
But something is wrong. When i try to render options list elements wrapped in divs, the names of the movies are hidden (?)
They are rendered, because i can still choose option, and after that it is showned as selected, but the input list is still broken, and CSS styles are not applied.
What I am missing ? Autocomplete and its styling is new for me.
The code:
<Autocomplete
freeSolo
id="free-solo-2-demo"
disableClearable
options={top100Films.map((option) => option.title)}
renderOption={(props, option) => {
return (
<li {...props}>
<div
sx={{
backgroundColor: "red",
color: "orange"
}}
>
{option.title}
</div>
</li>
);
}}
renderInput={(params) => (
<TextField
{...params}
label="Search input"
InputProps={{
...params.InputProps,
type: "search"
}}
/>
)}
/>
</Stack>
);
}
Heres the demo : https://codesandbox.io/s/freesolo-material-demo-forked-dupxol?file=/demo.js
TL;DR Just change option.title to option in renderOption prop. And use Box instead of div to apply styles.
I couldn't find it stated in documentation explicitly but apparently each of the elements passed to options is then passed to renderOption as option argument.
So since you already pass array of option.title strings to options you will need to refer to them just as option in renderOption prop.
The sx prop is used by MUI components. So please change div to MUI Box component inside renderOption. The Box was created specifically for such cases.

MUI Autocomplete - Make all options selected by default

I've be using this example to try and get the values in the autocomplete drop down to be automatically selected by default. I'm looking to get all the values to be selected when the page is loaded. Does anyone know how to do this?
Sandbox code :
https://codesandbox.io/s/s26gz?file=/demo.js:504-523
You can pass a defaultValue props to Autocomplete like this
<Autocomplete
options={options}
value={value}
defaultValue={top100Films}
...
/>
You can control the value of the Autocomplete by overriding the value/onChange props and use useState to set the initially selected options:
const [value, setValue] = React.useState(options);
return (
<Autocomplete
options={options}
value={value}
onChange={(e, v) => setValue(v)}
{...}
/>
);
Or if you're using uncontrolled mode, simply pass a defaultValue:
<Autocomplete
defaultValue={options}
{...}
/>

Handling onChange event for MaterialUI drop down element

I'm trying to validate the MaterialUI TextField (Country list) component wrapped with Autocomplete using onChange event and use it to enable the Submit button if the field (the country) is filled in. But I'm facing an issue once I'm not entering the country name by hands but selecting it from the dropdown. It looks like onChange event does not see the change in case of selecting from the drop down. (Sorry for formatting issues)
// countries: [a,b,c,d];
<Autocomplete
options={countries as CountryType[]}
<TextField
onChange={(event)=>{setFormValue({
...formValue,
country: event.target.value
})}}
/>
After this I'm using it on enabling the button:
<Button
disableElevation
disabled={formValue.country===""}
>
Submit
</Button>
Would be very appreciated on some suggestions.
While TextField's onChange method is obviously handling changes of the TextField. It doesn't fire on value selection. You're better off removing TextField's onChange handler and assign onInputChange property of the Autocomplete component that does exactly what you're looking for:
<Autocomplete
id="combo-box-demo"
options={countries}
...
onInputChange={(_, value) => {
setFormValue({
...formValue,
country: value
})
}}
renderInput={(params) => (
<TextField ... /> {/* without onChange handler */}
)}
/>

react-select function call on click event on the chip

Hi I am trying to change a state in my component when there is a click event on a particular chip rendered in the search bar. Is that possible to do?
I am aware of the multiValue multiValueLabel and I can for example change the background color of the chip with that, so I thought I could use those tags to change the state but I didn't have any luck.
I have attempted to find a solution with isSelected tag but I am always reading undefined in the states.isSelected when console.logged it.
I feel like I need a onClick() functionality somewhere but I can't figure it out. A bit of a guidance would be much appreciated!
I am sharing a live code here so maybe we can discuss over it.
if you want to validate if an option is selected you could use the prop: isOptionSelected
or
const onChange = selectedOptions => setSelected(selectedOptions);
with props
isMulti
value={selected}
onChange={onChange}
components={{
MultiValue: SortableMultiValue,
}}
You can attach onClick listener in MultiValueLabel component
<Select
isMulti={true}
components={{
MultiValueLabel: (props) => {
return (
<div onClick={() => console.log(props.data)}>
<components.MultiValueLabel {...props} />
</div>
);
}
}}
{...}
/>
Live Demo

Categories