Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React JS Material UI Autocomplete: Change Options

I want to use an Autocomplete field for my React JS Project. For the design of the UI I use Material UI. In the documentation you can see the following example:

<Autocomplete
                    required
                    id="combo-box-demo"
                    filterOptions={(x) => x}
                    value={this.state.departure}
                    options={top100Films}
                    getOptionLabel={(option) => option.title}
                    renderInput={(params) => <TextField {...params} label="Startpunkt" variant="outlined" />}
                />

The options objects have the following default value:

let top100Films = [
        { title: 'The Shawshank Redemption', year: 1994 },
        { title: 'Monty Python and the Holy Grail', year: 1975 },
    ];

For my purpose I want to dynamically change the options since I use an Rest API where I get the results for the input. My question is therefore how I can change the options dynamically when the user is typing.

like image 415
softwareUser Avatar asked Mar 02 '23 12:03

softwareUser


1 Answers

You can use onInputChange prop in your case:

      <Autocomplete
            required
            id='combo-box-demo'
            filterOptions={(x) => x}
            value={this.state.departure}
            options={top100Films}
            getOptionLabel={(option) => option.title}
            onInputChange={(event: object, value: string, reason: string) => {
              if (reason === 'input') {
                changeOptionBaseOnValue(value);
              }
            }}
            renderInput={(params) => (
              <TextField {...params} label='Startpunkt' variant='outlined' />
            )}
          />

Then you can define changeOptionBaseOnValue to handle your options.

like image 156
Arfina Arfwani Avatar answered Mar 05 '23 17:03

Arfina Arfwani