I have two components in my demo application (Autocomplete and Text Field). I want to show only one component at any given time. The condition is that when the user uses SLASH (/), it will show the Text Field component; otherwise, it will show Autocomplete.
I tried like this
export default function ComboBox() {
const [show, setShow] = React.useState(false);
const [value, setvalue] = React.useState('');
const onchange = (e) => {
console.log('ooo', e?.target?.value);
const value = e?.target?.value;
setvalue(value);
setShow((prevState) => {
const newState = value?.includes('/');
if (prevState !== newState) {
if (newState) {
setTimeout(() => {
document.getElementById('outlined-basic')?.focus();
}, 10);
} else {
setTimeout(() => {
document.getElementById('combo-box-demo')?.focus();
}, 10);
}
}
return newState;
});
};
return (
<div>
{show ? (
<TextField
id="outlined-basic"
label="Outlined"
variant="outlined"
value={value}
onChange={onchange}
/>
) : (
<Autocomplete
disablePortal
id="combo-box-demo"
options={top100Films}
value={value}
// defaultValue={'abc'}
onInputChange={onchange}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Movie" />}
/>
)}
</div>
);
}
here is my code
https://stackblitz.com/edit/react-pjhf7s?file=Demo.tsx
My initial rendering is correct; the Autocomplete component is visible. When the user enters the text ‘the/’, it correctly shows the Text Field component. However, when I remove the ‘/’, it shows the Autocomplete component, but without the text automatically populating in the Autocomplete component.
steps to reproduce
- Run application
- Enter “the” in autocomplete it will show filter list
- Enter “/” .. it will show text field with text “the/” . which correct.
- Remove “/”
- Autocomplete field is blank .. This is the issue
Expected output : after remove “/” it will show same behavior as point 2