reactjsmaterial-uimui-autocomplete

how to control mui-autocomplete popup/component


Can anyone suggest how to control if the mui-autocomplete is "open" or not? in other words, I wish toprogramatically control if & when an autocomplete's item list is displayed or not. ( I would later also need to control scrolling )

mui-autocomplete has an "open" property, if set to true the list of items is shown.

but it does not seem to work the other way around. in other words, initially, I wish that the items are not shown, the component should be "closed". thus i set the state variable i provide the autocomplete open property to false. when its false, the item list is never shown, pressing the "toggle" button does not work, and writing a valid value in the box does not work either. it looks like when the property open is set to false it overrides most of the components functions.

can anyone suggest a solution ?


Solution

  • if you wish to control the autocomplete component you need to store its open state somewhere and then manually give the component its control back using the onClose and onOpen functions as such

    import React from "react"
    import Autocomplete from '@mui/material/Autocomplete';
    import { Button, TextField } from "@mui/material";
    
    const options = [
        { label: 'The Shawshank Redemption', year: 1994 },
        { label: 'The Godfather', year: 1972 },
        { label: 'The Godfather: Part II', year: 1974 },
        { label: 'The Dark Knight', year: 2008 },
        { label: '12 Angry Men', year: 1957 },
        { label: "Schindler's List", year: 1993 },
        { label: 'Pulp Fiction', year: 1994 },
      ];
    export default function MyComponent() {
        const [open,setOpen]=React.useState(false);
    
        return(
            <>
        <Autocomplete
        options={options}
        open={open}
        renderInput={(params) => <TextField {...params} label="Movie" />}
        onOpen={()=>{setOpen(true)}}
        onClose={()=>{setOpen(false)}}
        />
        <Button variant="contained" color="primary" disableElevation onClick={()=>{
            setOpen((open)=>{
                return !open;
            });
        }}>toggle autocomplete</Button>
        </>
        )
    }
    

    the example above maintains the normal behavior of the autocomplete component while giving you control to open and close it elsewhere in the code.