I have an array of object that looks like this:
[
{
_id: "6311c197ec3dc8c083d6b632",
name: "Safety"
},
........
];
I load this array as potential Menu Items for my Select:
{categoryData &&
categoryData.map((cat: any) => (
<MenuItem key={cat._id} value={cat}>
<Checkbox
checked={categories.some((el: any) => el._id === cat._id)}
/>
<ListItemText primary={cat.name} />
</MenuItem>
))}
In my Select I have predefined value for it:
const [categories, setCategories] = useState([
{
name: "Safety",
_id: "6311c197ec3dc8c083d6b632"
}
]);
.......
<Select
labelId="demo-multiple-checkbox-label"
id="demo-multiple-checkbox"
multiple
value={categories}
onChange={(event: any) => {
const {
target: { value }
} = event;
console.log(value);
setCategories(value);
}}
input={<OutlinedInput label="Tag" />}
renderValue={(selected) => selected.map((cat) => cat.name).join(", ")}
>
The problem is I am unable to unselect(de-select) the predefined value. In stead of removing it from array of categories I got it once again in it.
Here is the sandbox example:
https://codesandbox.io/s/recursing-river-1i5jw8?file=/src/Select.tsx:632-757
I understand that values has to be exactly equal to be removed but how I can do that? What is wrong with this kind of handling?
Also I found this case as reference but still couldn't do it as in the case they use formik:
Unselect MUI Multi select with initial value
You can't directly save the Object as the value. You must use a unique string or stringify the entire object and store it as the value. And based on that value calculate the selected value rendered text. Here is something that will work for you.
Changes: use _id as the value instead of the entire object. And added a new selected value renderer.
import {
FormControl,
Select,
MenuItem,
InputLabel,
Checkbox,
ListItemText,
OutlinedInput
} from "#mui/material";
import React, { useState, useMemo } from "react";
const categoryData = [
{
_id: "6311c197ec3dc8c083d6b632",
name: "Safety"
},
{
_id: "6311c8e6ec3dc8c083d6b63b",
name: "Environment"
},
];
const SelectForm = () => {
const [categories, setCategories] = useState(["6311c197ec3dc8c083d6b632"]);
const selectedCategories = useMemo(() => {
let value = "";
categoryData.forEach((cat) => {
if (categories.some((catId: any) => catId === cat._id)) {
if (value) {
value += ", " + cat.name;
} else {
value = cat.name;
}
}
});
return value;
}, [categories]);
return (
<FormControl fullWidth>
<InputLabel id="demo-multiple-checkbox-label">Category</InputLabel>
<Select
labelId="demo-multiple-checkbox-label"
id="demo-multiple-checkbox"
multiple
value={categories}
onChange={(event: any) => {
const {
target: { value }
} = event;
console.log(value);
setCategories(value);
}}
input={<OutlinedInput label="Tag" />}
renderValue={() => selectedCategories}
>
{categoryData &&
categoryData.map((cat: any) => (
<MenuItem key={cat._id} value={cat._id}>
<Checkbox
checked={categories.some((catId: any) => catId === cat._id)}
/>
<ListItemText primary={cat.name} />
</MenuItem>
))}
</Select>
</FormControl>
);
};
export default SelectForm;
Initially, you have to pass an empty array while setting the state. This will solve your problem.
Code changes will look like this -
const [categories, setCategories] = useState([]);
I have component PhoneConformition which uses input :
<Flexbox>
{CODE_INPUTS.map((input, index) => (
<Controller
key={input.name}
name={input.name}
control={control}
defaultValue=""
// rules={{ required: true }}
render={(props) => (
<InputCode
{...props}
ref={inputListRefs.current[index]}
className={styles.phoneConfirmation__formInput}
onValueSet={() => handleOnValueSet(index)}
/>
)} // props contains: onChange, onBlur and value
/>
))}
</Flexbox>
Where InputCode is =
type Props = {
className?: string;
name: string;
onChange: (...event: any[]) => void;
onValueSet: (value: string) => void;
};
const InputCode = forwardRef<HTMLInputElement, Props>(
({ className, name, onChange, onValueSet }, ref) => {
const classNames = [styles.inputCode, className].join(" ");
const [valueState, setValueState] = useState<string>("");
const handleChange = (event: React.SyntheticEvent<HTMLInputElement>) => {
event.preventDefault();
};
const handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
const value: number = parseInt(event.key, 10);
if (!isNaN(value)) {
const valueString: string = value.toString();
setValueState(valueString);
onChange(valueString);
onValueSet(valueString);
}
};
return (
<div className={classNames}>
<input
ref={ref}
name={name}
className={styles.inputCode__input}
type="text"
onChange={handleChange}
onKeyPress={handleKeyPress}
value={valueState}
/>
</div>
);
}
);
export default InputCode;
BUT if i want to use the function on value set function where it focus on another function according to index.Everything is wokring instead of .focus
const handleOnValueSet = (index: number) => {
const formvalues = getValues();
onCodeChange(formvalues);
if (index + 1 < CODE_INPUTS.length) {
inputListRefs.current[index + 1].current?.focus();
}
}
.focus is not working with the onValueSet however with onChange or onKeyDown working correctly.
Found the solution. The issue was that the second onCodeChange call started before the first one finished.
I just added a setTimeOut of 10ms on the second call and it worked.
Thanks all
I'm having this Typescript error when using react-autosuggest with a custom input styled-component.
Types of property 'onChange' are incompatible. Type '(event: FormEvent, params: ChangeEvent) => void' is not assignable to type '(event: ChangeEvent) => void'.
Code:
(note that it's not complete, just relevant portions)
// styled.ts
export const Input = styled.input`
// styles
`;
// index.tsx
function renderInput(
inputProps: Autosuggest.InputProps<SuggestionSearch>,
placeholder: string
) {
// --> error here
return <Input {...inputProps} placeholder={placeholder} />;
}
const MyComponent = () => {
const autosuggestRef = React.useRef<
Autosuggest<SuggestionSearch, SuggestionSearch>
>(null);
const onChange = (event: React.FormEvent, { newValue }: ChangeEvent) =>
setValue(newValue);
const inputProps = {
value,
onChange,
onKeyPress: onEnterPress,
};
return (
<Autosuggest
ref={autosuggestRef}
renderInputComponent={props => renderInput(props, placeholder)}
inputProps={inputProps}
// other props
/>
)
}
Not sure how to fix this, as Autosuggest onChange function overrides the base input onChange prop.
I spent about all night on this problem myself. It seems that this is a bug. Here is the signature of the InputProps:
interface InputProps<TSuggestion>
extends Omit<React.InputHTMLAttributes<any>, 'onChange' | 'onBlur'> {
onChange(event: React.FormEvent<any>, params: ChangeEvent): void;
onBlur?(event: React.FocusEvent<any>, params?: BlurEvent<TSuggestion>): void;
value: string;
}
It seems we'll need to create our own Input component that take in this type of onChange signature or wrap this onChange in the standard onChange.
So, this is my approach:
const renderInputComponent = (inputProps: InputProps<TSuggestion>): React.ReactNode => {
const onChangeHandler = (event: React.ChangeEvent<HTMLInputElement>): void => {
inputProps.onChange(event, { newValue: event.target.value, method: 'type' });
};
return <Input {...inputProps} onChange={onChangeHandler} />;
}
Two potential bugs:
Notice that the event returned is React.ChangeEvent and not the React.FormEvent. Minor difference but it can be a problem in runtime if you actually use it and particular enough about the event.
The returned params: ChangeEvent only account for type event method. If you want others, like click, esc, etc..., you must supplement your own (via onKeyUp for example, and then call `onChange(...{method: 'esc'})
According to doc:
Note: When using renderInputComponent, you still need to specify the usual inputProps. Autosuggest will merge the inputProps that you provide with other props that are needed for accessibility (e.g. 'aria-activedescendant'), and will pass the merged inputProps to renderInputComponent.
you don't have to do this:
renderInputComponent={props => renderInput(props, placeholder)}
Simply pass the placeholder directly into your inputProps and that would be given right back to you in the renderInputComponent.
const inputProps = {
value,
onChange,
onKeyPress: onEnterPress,
placeholder: 'something!`
};
My problem is the onChange() on the renderInputComponent does not trigger the onSuggestionsFetchRequested.
If I do not use custom input (via renderInputComponent), then everything works fine - onSuggestionsFetchRequested got triggered and suggestion list showing.
Main component:
const MySearchBox: FC<MySearchBoxProps> = (props) => {
// Autosuggest will pass through all these props to the input.
const inputProps = {
placeholder: props.placeholder,
value: props.value,
onChange: props.onChange
};
return (
<Autosuggest
suggestions={props.suggestions}
onSuggestionsFetchRequested={props.onSuggestionsFetechRequested}
onSuggestionsClearRequested={props.onSuggestionsClearRequested}
getSuggestionValue={props.getSuggestionValue}
shouldRenderSuggestions={(value) => value.trim().length > 2}
renderSuggestion={(item: ISuggestion) => {
<div className={classes.suggestionsList}>{`${item.text} (${item.id})`}</div>;
}}
renderInputComponent={(ip: InputProps<ISuggestion>) => {
const params: InputProps<ISuggestion> = {
...ip,
onChange: props.onChange
};
return renderInput(params);
}}
inputProps={inputProps}
/>
);
};
export { MySearchBox };
Custom Input Component:
import React, { FC, ChangeEvent } from 'react';
import SearchIcon from '#material-ui/icons/Search';
import useStyles from './searchInput.styles';
import { Input } from '#material-ui/core';
type SearchInputBoxProps = {
loading?: boolean;
searchIconName: string;
minWidth?: number;
placeHolder?: string;
onChange?: (e: ChangeEvent, params: { newValue: string; method: string }) => void;
};
const SearchInputBox: FC<SearchInputBoxProps> = (props) => {
const classes = useStyles();
return (
<div className={classes.root}>
<div className={classes.searchIcon}>
<SearchIcon />
</div>
<Input
placeholder={props.placeHolder}
classes={{
root: classes.inputContainer,
input: classes.inputBox
}}
inputProps={{ 'aria-label': 'search' }}
onChange={(e) => {
const params: { newValue: string; method: string } = {
newValue: e.target.value,
method: 'type'
};
console.log(`e: ${JSON.stringify(params)}`);
if (props.onChange) props.onChange(e, params);
}}
//onMouseOut={(e) => alert(e.currentTarget.innerText)}
/>
</div>
);
};
export { SearchInputBox };
Render Function:
const renderInput = (inputProps: InputProps<ISuggestion>): React.ReactNode => {
return <SearchInputBox loading={false} onChange={inputProps.onChange} placeHolder={inputProps.placeholder} searchIconName={'search'} {...inputProps.others} />;
};
I had same problem.
I just had to cast HTMLElement into HTMLInputElement
Like below
const target = e.currentTarget as HTMLInputElement
Then, it works fine when you do
target.value
I can't get my component to show my autosuggestions.
It is observed in the console that my data is available and I sent it to this component using the suggestions prop, using Material UI AutoComplete component feature here I am trying to set my options, and these are changing as I type as it's handled in a parent component, but setting the values does not seem to reflect nor bring up my suggestions. I am very confused. my code is below.
import React, { FunctionComponent, FormEvent, ChangeEvent } from "react";
import { Grid, TextField, Typography } from "#material-ui/core";
import { CreateProjectModel, JobModel } from "~/Models/Projects";
import ErrorModel from "~/Models/ErrorModel";
import Autocomplete from "#material-ui/lab/Autocomplete";
type CreateProjectFormProps = {
model: CreateProjectModel;
errors: ErrorModel<CreateProjectModel>;
onChange: (changes: Partial<CreateProjectModel>) => void;
onSubmit?: () => Promise<void>;
suggestions: JobModel[];
};
const CreateProjectForm: FunctionComponent<CreateProjectFormProps> = ({
model,
errors,
onChange,
onSubmit,
suggestions,
}) => {
const [open, setOpen] = React.useState(false);
const [options, setOptions] = React.useState<JobModel[]>([]);
const loading = open && options.length === 0;
const [inputValue, setInputValue] = React.useState('');
React.useEffect(() => {
let active = true;
if (!loading) {
return undefined;
}
(async () => {
if (active) {
setOptions(suggestions);
}
})();
return () => {
active = false;
};
}, [loading]);
React.useEffect(() => {
if (!open) {
setOptions([]);
}
}, [open]);
const submit = async (event: FormEvent) => {
event.preventDefault();
event.stopPropagation();
await onSubmit();
};
const change = (name: string) => (event: ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value);
onChange({
[name]: event.target.value,
});
};
const getFieldProps = (id: string, label: string) => {
return {
id,
label,
helperText: errors[id],
error: Boolean(errors[id]),
value: model[id],
onChange: change(id),
};
};
return (
<Autocomplete
{...getFieldProps}
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
getOptionSelected={(option, value) => option.id === value.id}
getOptionLabel={(option) => option.id}
options={options}
loading={loading}
autoComplete
includeInputInList
renderInput={(params) => (
<TextField
{...getFieldProps("jobNumber", "Job number")}
required
fullWidth
autoFocus
margin="normal"
/>
)}
renderOption={(option) => {
return (
<Grid container alignItems="center">
<Grid item xs>
{options.map((part, index) => (
<span key={index}>
{part.id}
</span>
))}
<Typography variant="body2" color="textSecondary">
{option.name}
</Typography>
</Grid>
</Grid>
);
}}
/>
);
};
export default CreateProjectForm;
Example of my data in suggestions look like this:
[{"id":"BR00001","name":"Aircrew - Standby at home base"},{"id":"BR00695","name":"National Waste"},{"id":"BR00777B","name":"Airly Monitor Site 2018"},{"id":"BR00852A","name":"Cracow Mine"},{"id":"BR00972","name":"Toowoomba Updated"},{"id":"BR01023A","name":"TMRGT Mackay Bee Creek"},{"id":"BR01081","name":"Newman Pilot Job (WA)"},{"id":"BR01147","name":"Lake Vermont Monthly 2019"},{"id":"BR01158","name":"Callide Mine Monthly Survey 2019"},{"id":"BR01182","name":"Lake Vermont Quarterly 2019 April"}]
The problem in your code are the useEffects that you use.
In the below useEffect, you are actually setting the options to an empty array initially. That is because you autocomplete is not open and the effect runs on initial mount too. Also since you are setting options in another useEffect the only time your code is supposed to work is when loading state updates and you haven't opened the autocomplete dropdown.
The moment you close it even once, the state is updated back to empty and you won't see suggestions any longer.
React.useEffect(() => {
if (!open) {
setOptions([]);
}
}, [open]);
The solution is simple. You don't need to keep a local state for options but use the values coming in from props which is suggestions
You only need to keep a state for open
const CreateProjectForm: FunctionComponent<CreateProjectFormProps> = ({
model,
errors,
onChange,
onSubmit,
suggestions,
}) => {
const [open, setOpen] = React.useState(false);
const loading = open && suggestions.length === 0;
const [inputValue, setInputValue] = React.useState('');
const submit = async (event: FormEvent) => {
event.preventDefault();
event.stopPropagation();
await onSubmit();
};
const change = (name: string) => (event: ChangeEvent<HTMLInputElement>) => {
setInputValue(event.target.value);
onChange({
[name]: event.target.value,
});
};
const getFieldProps = (id: string, label: string) => {
return {
id,
label,
helperText: errors[id],
error: Boolean(errors[id]),
value: model[id],
onChange: change(id),
};
};
return (
<Autocomplete
{...getFieldProps}
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
getOptionSelected={(option, value) => option.id === value.id}
getOptionLabel={(option) => option.id}
options={suggestions}
loading={loading}
autoComplete
includeInputInList
renderInput={(params) => (
<TextField
{...getFieldProps("jobNumber", "Job number")}
required
fullWidth
autoFocus
margin="normal"
/>
)}
renderOption={(option) => {
return (
<Grid container alignItems="center">
<Grid item xs>
{options.map((part, index) => (
<span key={index}>
{part.id}
</span>
))}
<Typography variant="body2" color="textSecondary">
{option.name}
</Typography>
</Grid>
</Grid>
);
}}
/>
);
};
export default CreateProjectForm;
i noticed a few issues with your code, getFieldProps is being called without the id or name params which cause the page to not load. More importantly, you should consider following the autocomplete docs when passing and using props to it. for example:
renderInput={(params) => <TextField {...params} label="Controllable" variant="outlined" />}
i asked a few questions, pls let me know when you can get those answers so i may address all the issues that may come up.
Q1. should the user input provide relevant matches from the name property in your suggestions or just the id? for ex. if i type "lake", do you want to show BRO1182, Lake Vermont Quarterly 2019 April as a match?
Q2. how did you want to address the error case? i see you have a error model, but unsure how you wish to use it to style the autocomplete when an error occurs
Q3. are we missing a submit button? i see the onSubmit function but it's not used in our code.
Q4. is there a particular reason why you need the open and loading states?
below is what i attempted so far to show related matches from user input
import React, { FunctionComponent, FormEvent, ChangeEvent } from "react";
import { Grid, TextField, Typography } from "#material-ui/core";
import { CreateProjectModel, JobModel } from "~/Models/Projects";
import ErrorModel from "~/Models/ErrorModel";
import Autocomplete from "#material-ui/lab/Autocomplete";
type CreateProjectFormProps = {
model: CreateProjectModel;
errors: ErrorModel<CreateProjectModel>;
onChange: (changes: Partial<CreateProjectModel>) => void;
onSubmit?: () => Promise<void>;
suggestions: JobModel[];
};
const CreateProjectForm: FunctionComponent<CreateProjectFormProps> = ({
model,
errors,
// mock function for testing
// consider a better name like selectChangeHandler
onChange = val => console.log(val),
// consider a better name like submitJobFormHandler
onSubmit,
suggestions: options = [
{ id: "BR00001", name: "Aircrew - Standby at home base" },
{ id: "BR00695", name: "National Waste" },
{ id: "BR00777B", name: "Airly Monitor Site 2018" },
{ id: "BR00852A", name: "Cracow Mine" },
{ id: "BR00972", name: "Toowoomba Updated" },
{ id: "BR01023A", name: "TMRGT Mackay Bee Creek" },
{ id: "BR01081", name: "Newman Pilot Job (WA)" },
{ id: "BR01147", name: "Lake Vermont Monthly 2019" },
{ id: "BR01158", name: "Callide Mine Monthly Survey 2019" },
{ id: "BR01182", name: "Lake Vermont Quarterly 2019 April" }
]
}) => {
const [value, setValue] = React.useState<JobModel>({});
const loading = open && options.length === 0;
// this pc of code is not used, why?
const submit = async (event: FormEvent) => {
event.preventDefault();
event.stopPropagation();
await onSubmit();
};
const handleChange = (_: any, value: JobModel | null) => {
setValue(value);
onChange({
[value.name]: value.id
});
};
// consider passing in props instead
const getFieldProps = (id: string, label: string) => {
return {
id,
label,
// not sure what this is
helperText: errors[id],
// not sure what this is
error: Boolean(errors[id]),
value: model[id],
onChange: change(id)
};
};
return (
<Autocomplete
id="placeholder-autocomplete-input-id"
// for selection, use value see docs for more detail
value={value}
onChange={handleChange}
getOptionSelected={(option, value) => option.id === value.id}
getOptionLabel={option => option.id}
options={options}
loading={loading}
autoComplete
includeInputInList
renderInput={params => (
// spreading the params here will transfer native input attributes from autocomplete
<TextField
{...params}
label="placeholder"
required
fullWidth
autoFocus
margin="normal"
/>
)}
renderOption={option => (
<Grid container alignItems="center">
<Grid item xs>
<span key={option}>{option.id}</span>
<Typography variant="body2" color="textSecondary">
{option.name}
</Typography>
</Grid>
</Grid>
)}
/>
);
};
export default CreateProjectForm;
and you can see the code running in my codesandbox by clicking the button below
If I understand your code and issue right, you want -
React.useEffect(() => {
let active = true;
if (!loading) {
return undefined;
}
(async () => {
if (active) {
setOptions(suggestions);
}
})();
return () => {
active = false;
};
}, [loading]);
to run each time and update options, but the thing is, [loading] dependency setted like
const loading = open && suggestions.length === 0;
and not gonna trigger changes.
Consider doing it like so -
const loading = useLoading({open, suggestions})
const useLoading = ({open, suggestions}) => open && suggestions.length === 0;
I would like to call my onChange manually.
Here's my select with onChange (I pass onChangeSelect as a prop from parent component)
return(
<Form Control disabled={disabled}
<NativeSelect ref={ref} onChange={onChangeSelect}>
...
And I'd like to call that onChange every time my variable changes and is empty
useEffect(() => {
if (requiredSelect[0].length > 0 || id === "root1") { setDisabled(false) }
else { ref.current.value = ([[], []]); ref.current.onChange ; setDisabled(true); }
}, [requiredSelect])
And here's onChangeSelect in parent component
<Child onChangeSelect={(e) => rootChange(e)}>
and what it does
const rootChange = e => { setRootSelect(e.target.value.split(',')); }
The simplest solution here would be to change the definition of your rootChange function to accept the value instead of the event itself.
const rootChange = value => { setRootSelect(value.split(',')); }
// In parent:
<Child onChangeSelect={rootChange}>
// Select
<NativeSelect ref={ref} onChange={(e) => onChangeSelect(e.target.value)}>
You can trigger the function manually with:
onChangeSelect(whateverValueYouWant); // notice that you need the brackets when calling the function.
Answer in Typescript
//Child Component
type PropsType = {
onChange: (value: string) => void;
value: string;
};
const CustomInput: FC<PropsType> = (props: PropsType) => {
const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
props.onChange(event.target.value);
};
return (<input
onChange={onChange}
type="text"
value={props.value}></input>);
};
//Parent Component
const [input, setInput] = React.useState('');
<CustomInput
onChange={(value: string) => {
setInput(value);
}}
value={input}></CustomInput>