score:0
I kind of found one solution to deal with it on my own, after fiddling through documentation for some unrelated Problem. The solution includes
- Setting
value = {[...myStateVariable]}
- Using the reason parameter from the
onChange((event, newValue, reason)=>{....})
callback
<Autocomplete
multiple
id="tags-outlined"
options={students}
getOptionLabel={(option) => option.personalInfo.firstName+' '+option.personalInfo.lastName}
defaultValue={[...added]}
value={[...added]}
onChange={(e, newVal, reason)=>{
if(reason==="select-option"){
addChips(newVal)
} else if(reason==="remove-option"){
handleDelete(newVal)
}
}}
The HandleDelete and addChips method are as follows.
const [added, setAdded] = useState([...added2])
const handleDelete = (students)=>{
setAdded([...students])
}
const addChips = (students)=>{
if(added.length>= maxParticipation){
alert('Cannot add more participants')
}else{
setAdded([...students])
}
}
the 'newValue' is first intercepted by the 'onChange' callback where it's length is evaluated and if the length is greater than a limiting value, the value update is cancelled. (Notice, the onChange that causes abortion of the process is only the one where "reason" = 'select-option' ). P.S- (forgot to mention about the disable Options query) the "disable" attribute on Options could also be manipulated in the renderOptions to disable all the options after "newVal" reaches a given length. [ solution for that(disable options) given in detail by @justindra ]
score:0
I used slice
to limit the maximum limit on renderTags before rendering the chips
<Autocomplete
renderTags={(options, getTagProps) =>
options.slice(0, 5).map((option) => (
<Chip
icon={
<FaceIcon /> /*<Avatar color="primary" variant='outlined' size="small" className={classes.small}></Avatar>*/
}
label={option.personalInfo.firstName + ' ' + option.personalInfo.lastName}
color="primary"
variant="outlined"
{...getTagProps({})}
/>
))
}
/>
score:0
<Autocomplete
multiple
id="role"
options={rootStore.roleStore.listRole}
disableCloseOnSelect
value={rootStore.userStore.user.role}
onChange={(event, newValue) => {
setErrors({
...errors,
role: Utils.validate.single(
newValue,
Utils.constraintsUser.role
),
})
if (newValue.length > 2) {
alert("Please select max 2 labs")
} else {
rootStore.userStore.updateUser({
...rootStore.userStore.user,
role: newValue,
})
}
}}
getOptionLabel={(option) => option.description || ""}
renderOption={(option, { selected }) => (
<React.Fragment>
<Checkbox style={{ marginRight: 8 }} checked={selected} />
{option.description}
</React.Fragment>
)}
renderInput={(params) => (
<TextField
{...params}
variant="outlined"
label="Labs"
placeholder="Labs"
/>
)}
/>
perfect solution..
score:0
My solution,I think it's the most properly way:
<Autocomplete
value={selectedTags}
onChange={(ev, value: Tag[]) => {
if (value.length <= 3) {
setSelectedTags(value);
} else {
return;
}
}}
/>;
score:0
In my case, this worked fine.
onChange={(e, newVal) => {
if (newVal > 3) {
newVal.pop();
}
setAdded([...newVal]);
}
Though the documentation explains that the value
parameter of onChange
prop is the new value, the actual content seems the array of all selected options.
And the last element in the value
array is the newly selected option by the current change event. Therefore the code snippet above eliminates the exceeding element against the limited number (3 as above).
The latter type (Array<T>
) for value
parameter in the documentation is the case.
score:1
Autocomplete
added getOptionDisabled
prop that can be used to disable all non selected options after maximum number of options is selected.
const a = ({limit = 3})=> {
const [limitReached, setLimitReached] = useState(false);
const [values, setValues] = useState([]);
const onSelect = useCallback((newValues) => {
setValues(newValues);
setLimitReached(newValues.length >= limit);
}, [limit]);
const checkDisable = useCallback(option => limitReached && !values.includes(option), [limitReached, values]);
return <Autocomplete
getOptionDisabled={checkDisable}
multiple
onChange={onSelect}
options={options}
value={values}
/>
}
score:2
Ran into similar issue recently. This is what I ended up doing. Basically you have to set the disabled flag on the chip itself directly, so it disables the text input, but not the chip. So you can still delete each chip.
export const AutoCompleteWithLimit: React.FC<Props> = ({
disabled = false,
limit = 2,
}) => {
const [disableInput, setDisableInput] = useState<boolean>(
value.length >= limit
);
return (
<Autocomplete
// Set disabled based on input
disabled={disabled || disableInput}
multiple
renderTags={(tagValue, getTagProps) =>
tagValue.map((option, index) => (
<Chip
key={index}
label={option.name}
{...getTagProps({ index })}
// Set disable explicitly after getTagProps
disabled={disabled}
/>
))
}
onChange={(_event: any, newValue: any[]) => {
// do something else
// set the disable input
setDisableInput(newValue.length >= limit);
}}
/>
);
};
Source: stackoverflow.com
Related Query
- How Can i limit the maximum number of options that can be selected in a Material UI lab Autocomplete component
- How to set max number of items that can be selected in react-select?
- How can i remove employees from the array that have endDate property higher than current selected month?
- How can I count the number of components on a page that have been connected with redux' connect() function?
- How can I access the custom target attribute within material UI select options in React js
- How can I prevent material-ui Select options to be opened when clicking on particular area of the selected option
- How to limit the number of selected check-boxes in React JS?
- Material UI Popper over TextField how to keep popper open if the popper options are selected
- How to limit the number of options in a select?
- How can I enable on row click and redirect to a new tab with the following data of that selected row?
- How can I search only the selected options in multivalue react-select?
- How can I limit the number of characters per line in a textArea using React?
- material UI - How can I change the font size of the label in FormControlLabel
- How to change the text color of the selected row in material ui table
- How i can limit the items in the FlatList and add load more?
- How to limit the text filed length with input type number in React JS and prevent entry of E,e, -, + etc
- How can I remove line above the accordion of Material UI?
- How can I change the width of Material UI Autocomplete popover
- In redux-observable - How can I dispatch an action "mid-stream" without returning the value of that action?
- How can you incorporate the error page that create-react-app uses into a custom project?
- How can I change the label size of a material ui TextField?
- Material UI - Facing an issue that drop down options are coming below the modal window footer
- How can I cache data that I already requested and access it from the store using React and Redux Toolkit
- In Chrome Developer Tools, how can I disable the highlight around elements that refresh?
- How do I manage state on a React component that can have state changed from the parent or from events upon it?
- How do we return a Promise from a store.dispatch in Redux - saga so that we can wait for the resolve and then render in SSR?
- how can I make a scrollable component that scrolls to the latest children components automatically when I append a child component?
- How do i annotate React.forwardRef with jsdoc comments so that intellisense can show up for the underlying component?
- How can I check the type of material ui theme in react js? (light or dark)
- React useEffect calls API too many time, How can I limit the API call to only once when my component renders?
More Query from same tag
- How to show success or error message based on the response of the api in React js
- Modify one state property in two Reducers in Redux
- Can't bind callback function in React
- MaterialUI TextField : changing background color is not working as it is supposed to
- Extending base class property in Typescript
- Updating Redux Store from changes in child components
- How can I effectively store data in array?
- React object how to wrap more than one component
- React with Redux and Router - server rendering
- Any good debug tutorial for React.js
- How to set the background color of material ui drawer component with styled-components?
- React typescript error: Element implicitly has an 'any' type
- Testing React Select component
- How does React Strict Mode works?
- How to dynamically add a class to manual class names?
- ES6 Function binding gets undefined (this.state captures the values)
- How to use React Hooks to capture the last input letter
- React - how to display all products using dropdown?
- Trying to export data to csv file from my firebase data gives undefined
- Errors on 'concurrently "npm run server" "npm run client" with MERN
- place gtag event snippet head Gatsby/React site
- How does this Form gets submited?
- Using maps over template literals
- How to Access forLoop data outside the scope
- Unit test: simulate the click event of child component in parent using enzyme
- Error when reactjs requests from Django server (403 error / CORS)
- Why does this cause an endless loop? I don't understand
- Unexpected blue border while typing text react-select
- Material UI with React
- Simple Fetch API Post Request Fails No Matter What