I have an autocomplete React Material component that fetches data from the server. However, in some scenarios, I want to convert the autocomplete to a text field if a user enters a slash (‘/’).
here it was suggested to use freesolo property
how to show textfield or 2 different component in react js?
https://mui.com/material-ui/react-autocomplete/#free-solo
I tried to using this but not able to apply .. I also want to fetch the entered value..
here is my code
https://stackblitz.com/edit/vitejs-vite-sctdxd?file=src%2FApp.tsx,src%2Findex.css,src%2Fmain.tsx,package.json&terminal=dev
export default function App() {
const [options, setOptions] = React.useState<typeof top100Films>([]);
const [open, setOpen] = React.useState(false);
const loading = open && options.length === 0;
const defaultValues = {
movie: null,
};
React.useEffect(() => {
let active = true;
if (!loading) {
return undefined;
}
(async () => {
if (active) {
setOptions([...top100Films]);
}
})();
return () => {
active = false;
};
}, [loading]);
React.useEffect(() => {
if (!open) {
setOptions([]);
}
}, [open]);
const { registerState, handleSubmit, getValues } = useHookForm({
defaultValues,
});
const onSubmit = (_data: typeof defaultValues) => {
console.log(_data);
};
return (
<div className="App">
{JSON.stringify(getValues(), 2, null)}
<form onSubmit={handleSubmit(onSubmit)}>
<h2>Asynchronous `Request` state can be optained</h2>
<Grid container spacing={3} sx={{ minHeight: 120 }}>
<HookAutoComplete
{...registerState('movie')}
autocompleteProps={{
options,
autoHighlight: true,
isOptionEqualToValue: ({ label }, value) => label === value.label,
loading,
open,
onOpen: () => {
setOpen(true);
},
onClose: () => {
setOpen(false);
},
}}
textFieldProps={{
label: 'Movie',
placeholder: 'The...',
InputProps: {
endAdornment: (
<>
{loading ? (
<CircularProgress color="inherit" size={20} />
) : null}
</>
),
},
onChange: (event) => {
console.log('event', event.target.value);
},
}}
gridProps={{
xs: 12,
}}
rules={{
required: {
message: 'Required',
value: true,
},
}}
/>
</Grid>
<Grid>
<Button type="submit" variant="contained">
Submit
</Button>
</Grid>
</form>
</div>
);
}
Main issue : how to fetch user enter value ? Currently it is showing NULL if user enter “the/as”
why ?