Disable backspace deleting of options in Autocomplete - javascript

I want to use an Autocomplete (from the Material-Ui library) component from material ui to select multiple options, and those options should not be able to be removed (directly) by the user.
The problem I'm facing is that the user can delete the options from the Autocomplete if they focus the component and press backspace as if they are deleting text.
Code
This is the component I'm using:
<Autocomplete multiple
options={options}
getOptionLabel={option => option.title}
renderInput={params =>
<TextField {...params} label="Autocomplete" variant="outlined" />
}
onChange={this.onAutocompleteChange.bind(this)}
getOptionSelected={(option: Option, value: Option) => option.value === value.value}
filterSelectedOptions={true}
renderTags={(tagValue, getTagProps) =>
tagValue.map((option, index) => (
<Chip key={option.value} label={option.title} color="primary" />
))
}
disableClearable={true}
/>
What I tried
Disabling the TextField from the renderInput prop with disable={true} has no effect.
Adding InputProps={{ disabled: true }} or InputProps={{ readOnly: true }} to TextField disables the Autocomplete completely.
Adding ChipProps={{ disabled: true }} to the Autocomplete has no effect.
Thanks for reading!

To control this aspect, you need to use a controlled approach to the Autocomplete's value as demonstrated in this demo.
In the documentation for the onChange prop you will find the following:
onChange Callback fired when the value changes.
Signature:
function(event: object, value: T | T[], reason: string) => void
event: The event source of the callback.
value: The new value of the component.
reason: One of "create-option", "select-option", "remove-option", "blur" or "clear".
The third argument to onChange is the "reason" for the change. In your case, you want to ignore all of the "remove-option" changes:
onChange={(event, newValue, reason) => {
if (reason !== "remove-option") {
setValue(newValue);
}
}}
Here's a full working example:
import React from "react";
import TextField from "#material-ui/core/TextField";
import Autocomplete from "#material-ui/lab/Autocomplete";
import Chip from "#material-ui/core/Chip";
const options = ["Option 1", "Option 2"];
export default function ControllableStates() {
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
multiple
value={value}
disableClearable
onChange={(event, newValue, reason) => {
if (reason !== "remove-option") {
setValue(newValue);
}
}}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
id="controllable-states-demo"
options={options}
style={{ width: 300 }}
renderInput={params => (
<TextField {...params} label="Controllable" variant="outlined" />
)}
renderTags={(tagValue, getTagProps) =>
tagValue.map((option, index) => (
<Chip key={option} label={option} color="primary" />
))
}
/>
</div>
);
}

Related

How to clear data on Select multiple when typing on another textfield using reactjs

This is my current code, what I want here is after selecting on Select option (CHIP) and if the user type on the textfield I want to clear what the user selected on CHIP, What should I do to get what i want functionality?
const names = [
'Oliver Hansen',
'Van Henry',
'April Tucker',
];
function getStyles(name, personName, theme) {
return {
fontWeight:
personName.indexOf(name) === -1
? theme.typography.fontWeightRegular
: theme.typography.fontWeightMedium,
};
}
export default function MultipleSelectChip() {
const theme = useTheme();
const [personName, setPersonName] = React.useState([]);
const handleChange = (event) => {
const {
target: { value },
} = event;
setPersonName(
// On autofill we get a stringified value.
typeof value === 'string' ? value.split(',') : value
);
};
const handleChangeTextField = (event) => {
setPersonName(null);
};
return (
<div>
<FormControl sx={{ m: 1, width: 300 }}>
<InputLabel id="demo-multiple-chip-label">Chip</InputLabel>
<Select
labelId="demo-multiple-chip-label"
id="demo-multiple-chip"
multiple
value={personName}
onChange={handleChange}
input={<OutlinedInput id="select-multiple-chip" label="Chip" />}
renderValue={(selected) => (
<Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
{selected.map((value) => (
<Chip key={value} label={value} />
))}
</Box>
)}
MenuProps={MenuProps}
>
{names.map((name) => (
<MenuItem
key={name}
value={name}
style={getStyles(name, personName, theme)}
>
{name}
</MenuItem>
))}
</Select>
<TextField
variant="outlined"
label="Type anything to remove the value of Chip"
onChange={handleChangeTextField} />
</FormControl>
</div>
This is my current code, what I want here is after selecting on Select option (CHIP) and if the user type on the textfield I want to clear what the user selected on CHIP, What should I do to get what i want functionality?
I would set your textfield to be controlled (ie backed by a state variable) and add an effect hook to watch it.
When it receives a value, clear the selected names by setting personNames back to an empty array.
const [text, setText] = useState("");
useEffect(() => {
if (text) {
setPersonName([]);
}
}, [text]);
const handleChangeTextField = ({ target: { value } }) => {
setText(value);
};
<TextField
value={text}
variant="outlined"
label="Type anything to remove the value of Chip"
onChange={handleChangeTextField}
/>
You might also want to clear the text field when selecting names by adding this into handleChange...
setText("");

Material-ui Autocomplete: Add a value to startAdornment

I have autocomplete with multiple selection permission.
https://codesandbox.io/s/bold-jackson-dkjmb?file=/src/App.js
In the example I have 3 options for cities. How can I manually add automatic added value in TextField when something is selected?
In other words here:
renderInput={(params) => {
console.log(params);
return (
<TextField
{...params}
variant="outlined"
label="Cities"
placeholder="Enter cities"
autoComplete="off"
InputProps={{
...params.InputProps,
endAdornment: (
<React.Fragment>
{params.InputProps.endAdornment}
</React.Fragment>
)
}}
/>
);
}}
I want to be able to add to params.InputProps.startAdornment a value before rendering the textfield.
as every selected object seems to be very complex object, how I can do this manually(It is too complicated to push())? Any ideas how I can add object like this:
manually?
the value of startAdornment is undefined until a value is chosen from the dropdown/checkbox. So, you could add startAdornment property to the InputProps like below,
import { Chip } from '#material-ui/core';
import { makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles((theme) => ({
chip: {
margin: theme.spacing(0.5, 0.25)
}
}));
const classes = useStyles();
const handleDelete = (item) => () => {...};
renderInput={(params) => {
console.log(params);
return (
<TextField
{...params}
variant="outlined"
label="Cities"
placeholder="Enter cities"
autoComplete="off"
InputProps={{
...params.InputProps,
startAdornment: (
<Chip
key={"manual"}
tabIndex={-1}
label={"manually added"}
className={classes.chip}
onDelete={handleDelete("blah")}
deleteIcon // requires onDelete function to work
/>
),
endAdornment: (
<React.Fragment>
{params.InputProps.endAdornment}
</React.Fragment>
)
}}
/>
);
}}
The other solution didn't work 100% from myside,
As it adds the automatic field,
But new selected options -> are selected but chips not showing next to the automatic added option!!
So to fix this problem I made a few changes:
<TextField
{...params}
variant="outlined"
label="Cities"
placeholder="Enter cities"
autoComplete="off"
InputProps={{
...params.InputProps,
startAdornment: (
<>
<Chip
key={"manual"}
tabIndex={-1}
label={"manually added"}
className={classes.chip}
onDelete={handleDelete("blah")}
deleteIcon // requires onDelete function to work
/>
<React.Fragment> //the change
{" "}
{params.InputProps.startAdornment}{" "}. //the change
</React.Fragment>
</>
),
}}
endAdornment: (
<React.Fragment>
{params.InputProps.endAdornment}
</React.Fragment>
)
}}
/>

React Autocomplete with Material UI

I'm implementing a component Autocomplete using Material UI library.
But there's a problem - I'm not sure how to pass value and onChange properly, because I have a custom implementation of TextField that requires value and onChange as well. Should I pass value and onChange twice - to Autocomplete and TextField? Or maybe there's a better solution? Would appreciate any help!
Here's my code:
import { Autocomplete as MuiAutocomplete } from '#material-ui/lab'
import { FormControl } from 'components/_helpers/FormControl'
import { useStyles } from 'components/Select/styles'
import { Props as TextFieldProps, TextField } from 'components/TextField'
export type Props = Omit<TextFieldProps, 'children'> & {
options: Array<any>
value: string
onChange: (value: string) => void
disabled?: boolean
}
export const Autocomplete = (props: Props) => {
const classes = useStyles()
return (
<FormControl
label={props.label}
error={props.error}
helperText={props.helperText}
>
<MuiAutocomplete
options={props.options}
// value={props.value}
// onChange={event =>
// props.onChange((event.target as HTMLInputElement).value as string)
// }
classes={{
option: classes.menuItem,
}}
disabled={props.disabled}
getOptionLabel={option => option.label}
renderInput={params => (
<TextField
{...params}
placeholder={props.placeholder}
value={props.value}
onChange={props.onChange}
/>
)}
renderOption={option => {
return <Typography>{option.label}</Typography>
}}
/>
</FormControl>
)
}```
Material UI has props built in to handle the state of the Autocomplete vs input values.
You can see it in use in the docs here: https://material-ui.com/components/autocomplete/#controllable-states
In your example, you would want to add the inputChange and onInputChange props to the Autocomplete component. These will get passed down to your TextField through the params passed to the renderInput function.
So your final code would look something like the below snippet copied from the linked documentation:
<Autocomplete
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
inputValue={inputValue}
onInputChange={(event, newInputValue) => {
setInputValue(newInputValue);
}}
id="controllable-states-demo"
options={options}
style={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Controllable" variant="outlined" />}
/>
import React, { useEffect, useState } from "react";
import { Autocomplete } from "#mui/material/node";
import { Controller, useFormContext } from "react-hook-form";
import { TextField } from "#mui/material";
import PropTypes from "prop-types";
const valueFunc = (arr, id) => {
const temp = arr.length > 0 && arr?.find((element) => element.id === id);
return temp;
};
AutocompleteSearch.propTypes = {
options: PropTypes.arrayOf({
title: PropTypes.string,
id: PropTypes.string,
}),
name: PropTypes.string,
};
export default function AutocompleteSearch({
name,
options,
label,
id,
...other
}) {
const [temp, setTemp] = useState({});
const { control, setValue } = useFormContext();
useEffect(async () => {
const found = valueFunc(options, id);
await setTemp(found);
}, [options, id]);
return (
<Controller
control={control}
name={name}
rules={{ required: true }}
render={({ fieldState: { error } }) => (
<>
<div >
<Autocomplete
id="controllable-states-demo"
onChange={(_, v) => {
setValue(name, v?.id);
setTemp(v);
}}
onBlur={(e) => {
e.target.value == "" && setValue(name, "");
}}
value={temp}
options={options}
getOptionLabel={(item) => (item.title ? item.title : "")}
renderInput={(params) => (
<>
<TextField
{...params}
label={label}
InputLabelProps={{
style: {
fontSize: "14px",
fontWeight: "400",
color: "#FF5B00",
},
}}
size="small"
error={temp === null && !!error}
helperText={temp === null && error?.message}
{...other}
/>
</>
)}
/>
</div>
</>
)}
/>
);
}
<AutocompleteSearch
name="pharmacy_group_title"
label="Pharmacy Group"
options={pharmacyGroups} // Array {id , title}
id={defaultValues?.pharmacy_group_title} // ID
/>

Material UI - How to remove focus on autocomplete once an option is selected?

I am using an autocomplete component for my search. It works well for desktop but on mobile, the keyboard remains open once an option has been selected even though it redirects to another page.
<Autocomplete
id="free-solo-demo"
value={""}
className={classes.auto}
onChange={(event, value) => searchFunc(value)}
options={items.map((item) => item.item)}
renderInput={(params) => (
<TextField
label="Search..."
{...params}
InputProps={{
...params.InputProps,
disableUnderline: true,
classes: { input: classes.input },
}}
value={search}
/>
)}
/>
Search function:
const searchFunc = (value) => {
if (value) {
const param = items.filter((item) => item.item === value)[0].id;
setSearch("");
history.push(`/details/${param}`);
}
};
I want the mobile keyboard to close once an item has been selected!! Thank you :)

Material UI autocomplete with redux-form values getting destroyed

I'm trying to use Material UI's autocomplete component with redux wizard form
I was able to link the autocomplete provided by material UI but when i go back to previous page and come back to the second page where the autocomplete fields are, the field gets destroyed despite having destroyOnUnmount set to false. (All other fields doesn't get destroyed but only the fields in page 2 which uses material UI autocomplete feature) Actually I dont think it's getting destroyed because the value is still there you just can't see it in the input
Also When I click Submit, the Main Hobby section's value gets through but the multiple hobby section's value doesnt get through. Can anyone have a look and see what's wrong? Thanks
You need to define the value attribute of AutoComplete to show the selected values when you visit the form again.
You must note that the two fields in Hobby form need to be defined with different name
Also the onChange value of multi select AutoComplete need to inform reduxForm about the change
MultipleComplete.js
import React from "react";
import { TextField } from "#material-ui/core";
import { Autocomplete } from "#material-ui/lab";
const hobbies = [
{ title: "WATCHING MOVIE" },
{ title: "SPORTS" },
{ title: "MUSIC" },
{ title: "DRAWING" }
];
const MultipleComplete = ({
input,
meta: { touched, error, submitFailed }
}) => {
const { onChange, ...rest } = input;
return (
<div>
<Autocomplete
multiple
limitTags={2}
value={input.value || []}
id="multiple-limit-tags"
options={hobbies}
onChange={(e, newValue) => {
onChange(newValue);
}}
getOptionLabel={option => option.title}
getOptionSelected={(option, value) => option.title === value.title}
renderInput={params => (
<TextField
{...params}
variant="outlined"
placeholder="Choose Multiple Hobbies"
fullWidth
/>
)}
/>
</div>
);
};
export default MultipleComplete;
AutoHobbyComplete.js
import React from "react";
import { TextField } from "#material-ui/core";
import { Autocomplete } from "#material-ui/lab";
const hobbies = [
{ title: "WATCHING MOVIE" },
{ title: "SPORTS" },
{ title: "MUSIC" },
{ title: "DRAWING" }
];
const AutoHobbyComplete = ({
input,
meta: { touched, error, submitFailed }
}) => {
const getSelectedOption = () => {
return hobbies.find(o => o.title === input.value);
};
const { onChange, ...rest } = input;
return (
<div>
<Autocomplete
autoSelect
value={getSelectedOption()}
options={hobbies}
autoHighlight
getOptionLabel={option => option.title}
onChange={(event, newValue) => onChange(newValue)}
getOptionSelected={(option, value) => {
return option.title === value.title || option.title === input.value;
}}
renderInput={params => {
return (
<TextField
{...params}
{...rest}
value={input.value}
variant="outlined"
fullWidth
/>
);
}}
/>
</div>
);
};
export default AutoHobbyComplete;
It seems that youre correct, the value just isnt being displayed properly. If you are able to get the value from your redux form you can pass that value as an inputValue to the autocomplete. This will display the value in the text box. Make sure to use inputValue and not value.
<Autocomplete
inputValue={//this is where your redux form value should be displayed}
autoSelect
options={hobbies}
autoHighlight
getOptionLabel={option => option.title}
onChange={(event, newValue) => console.log(newValue)}
getOptionSelected={(option, value) => option.title === value.title}
renderInput={params => (
<TextField {...params} {...input} value="test" variant="outlined" fullWidth />
)}
/>

Categories

Resources