I’m coding a component to facility the use of material-ui React Autocomplete component, It new component has a few props then return the React Autocomplete component with its own props assigned, how Can I override the React Autocomplete prop “onChange” in some situations where I need to add additional code lines?
import React from 'react';
import './CustomAutocomplete.css';
import { Autocomplete, createFilterOptions } from '@material-ui/lab';
import { TextField } from '@material-ui/core';
interface CustomAutocompleteProps {
placeholder: string;
options: any[];
optionSelected: any;
setOptionSelected: (newValue: any) => void;
startSearchLength: number;
optionsSuggestionLimit: number;
}
export const CustomAutocomplete = (props: CustomAutocompleteProps) => {
const defaultFilterOptions = createFilterOptions();
const filterOptions = (options, state) => {
return defaultFilterOptions(options, state).slice(
0,
props.optionsSuggestionLimit
);
};
return (
<Autocomplete
placeholder={props.placeholder}
filterOptions={filterOptions}
value={
props.options.length === 1 ? props.options[0] : props.optionSelected
}
options={props.options ? props.options : []}
disabled={props.options.length === 1}
getOptionSelected={(option, value) => option.name === value.name}
getOptionLabel={(option) => option.name || ''}
onChange={(event: any, newValue: any) => {
props.setOptionSelected(newValue);
}}
renderInput={(params) => (
<TextField
{...params}
variant="standard"
placeholder={props.placeholder}
onChange={(event: any) => {
event.target.value.length > props.optionsSuggestionLimit &&
props.setOptionSelected(event.target.value);
}}
/>
)}
/>
);
};
In some cases I need to add more set useState in onChange props but if I add it in the CustomAutocomplete component it will attempt to execute in every import. How can I overried and called just in a specific situation?
onChange={(event: any, newValue: any) => {
setOptionSelected(newValue);
setoptionSelected2(newValue);
setOptionSelected3(newValue);
}}
Do you have any idea? Thanks!